How to display my 404 page in Nancy?

后端 未结 2 1807
别跟我提以往
别跟我提以往 2021-02-14 14:04

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:55

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

提交回复
热议问题