如何在南希显示我的404页面?

时间:2013-04-22 16:52:01

标签: asp.net .net nancy

我需要在Nancy中显示我的404错误页面,如此

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

怎么做?

2 个答案:

答案 0 :(得分:13)

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 :(得分:11)

您只需要提供IStatusCodeHandler界面的实现(它将由Nancy自动选取)。

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

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