NancyFX - 自定义404处理程序覆盖每404响应

时间:2013-08-25 13:55:45

标签: c# nancy

我为NancyFX做了我的自定义404处理程序,它运行正常,但是有一个问题。问题是它甚至覆盖了我想发送404代码的那些请求,但是我的自定义消息是“找不到用户”。

处理程序

public class NotFoundHandler : IStatusCodeHandler
{
    public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
    {
        if (statusCode == HttpStatusCode.NotFound)
        {
            // How to check here if the url actually exists?
            // I don't want every 404 request to be the same
            // I want to send custom 404 with Response.AsJson(object, HttpStatusCode.NotFound)
            return true;
        }

        return false;
    }

    public void Handle(HttpStatusCode statusCode, NancyContext context)
    {
        context.Response = new TextResponse(JsonConvert.SerializeObject(new { Message = "Resource not found" }, Formatting.Indented))
        {
            StatusCode = statusCode,
            ContentType = "application/json"
        };
    }
}

问题

Get["/"] = _ =>
{
    // This will not show "User not found", instead it will be overriden and it will show "Resource not found"
    return Response.AsJson(new { Message = "User not found" }, HttpStatusCode.NotFound);
};

1 个答案:

答案 0 :(得分:2)

您可以决定要在IStatusCodeHandler实施中处理哪些回复。现在,您只是检查状态代码本身,而不添加上下文。你可以做的(例如)如果它不包含符合某个标准的响应,例如类型为context.Response

,则只覆盖JsonResponse
    if(!(context.Response Is JsonResponse))
    {
            context.Response = new TextResponse(JsonConvert.SerializeObject(new { Message = "Resource not found" }, Formatting.Indented))
            {
                StatusCode = statusCode,
                ContentType = "application/json"
            };
    }

由于您可以访问完整的NancyContext,因此您还可以访问整个RequestResponse(由请求管道中的路由或其他内容返回)。此外,如果您需要更多控制,您可以在NancyContext.Items中粘贴任意元数据。

希望这有帮助