How to display my 404 page in Nancy?

一曲冷凌霜 提交于 2019-12-03 12:13:20

The answer from nemesv is correct, but I just wanted to add an example using the ViewRenderer instead of the 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;
    }
}

You just need to provide an implementation of the IStatusCodeHandler interface (it will be picked up automatically by Nancy).

In the HandlesStatusCode method return true for the HttpStatusCode.NotFound.

And in the Handle method you need to set the Response property on the NancyContext with a response containing your error page content. You can use for example the 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;            
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!