【问题标题】:NancyFX - Custom 404 handler overrides every 404 responseNancyFX - 自定义 404 处理程序覆盖每个 404 响应
【发布时间】:2013-08-25 23:22:35
【问题描述】:

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

【问题讨论】:

    标签: c# nancy


    【解决方案1】:

    您决定要在 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

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-19
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 2016-06-26
      • 2010-11-10
      相关资源
      最近更新 更多