10

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

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

怎么做?

4

2 回答 2

12

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;
    }
}
于 2014-02-22T10:09:51.187 回答
11

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

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

在该Handle方法中,您需要使用包含错误页面内容的响应来设置Response属性。NancyContext您可以使用例如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;            
    }
}
于 2013-04-22T20:14:00.817 回答