3

我为 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);
};
4

1 回答 1

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"
            };
    }

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

希望这可以帮助

于 2013-08-25T15:22:35.067 回答