【问题标题】:How to display my 404 page in Nancy?如何在 Nancy 中显示我的 404 页面?
【发布时间】:2013-04-15 16:07:51
【问题描述】:

我需要像这样在 Nancy 中显示我的 404 错误页面

if (ErrorCode == 404)
{
  return View["404.html"];
}

怎么做?

【问题讨论】:

  • 一定要添加 Nancy.ErrorHandling 命名空间。

标签: asp.net .net nancy


【解决方案1】:

nemesv 的答案是正确的,但我只是想添加一个使用 ViewRenderer 而不是 GenericFileResponse 的示例。

public class MyStatusHandler : IStatusCodeHandler
{
    private IViewRenderer viewRenderer;

    public MyStatusHandler(IViewRenderer viewRenderer)
    {
        this.viewRenderer = viewRenderer;
    }

    public bool HandlesStatusCode(HttpStatusCode statusCode,
                                  NancyContext context)
    {
        return statusCode == HttpStatusCode.NotFound;
    }

    public void Handle(HttpStatusCode statusCode, NancyContext context)
    {
        var response = viewRenderer.RenderView(context, "/status/404");
        response.StatusCode = statusCode;
        context.Response = response;
    }
}

【讨论】:

  • 这是更好的方法,因为它允许视图引擎和布局。 +1
  • 您可以通过使用WithStatusCode 扩展来进一步改进这一点,使Handle 成为单行:context.Response = viewRenderer.RenderView(context, "/status/404").WithStatusCode(statusCode);
【解决方案2】:

您只需要提供IStatusCodeHandler 接口的实现(Nancy 会自动获取)。

HandlesStatusCode 方法中,为HttpStatusCode.NotFound 返回true。

Handle 方法中,您需要在NancyContext 上设置Response 属性,并使用包含错误页面内容的响应。例如,您可以使用GenericFileResponse:

public class My404Hander : IStatusCodeHandler
{
    public bool HandlesStatusCode(HttpStatusCode statusCode, 
                                  NancyContext context)
    {
        return statusCode == HttpStatusCode.NotFound;
    }

    public void Handle(HttpStatusCode statusCode, NancyContext context)
    {
        var response = new GenericFileResponse("404.html", "text/html");
        response.StatusCode = statusCode;
        context.Response = response;            
    }
}

【讨论】:

    猜你喜欢
    • 2015-08-15
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    相关资源
    最近更新 更多