How to display my 404 page in Nancy?

后端 未结 2 1749
梦毁少年i
梦毁少年i 2021-02-14 14:11

I need to display my 404 error page in Nancy like this

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

How to do it?

2条回答
  •  礼貌的吻别
    2021-02-14 14:52

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

提交回复
热议问题