我需要像这样在 Nancy 中显示我的 404 错误页面
if (ErrorCode == 404)
{
return View["404.html"];
}
怎么做?
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;
}
}
您只需要提供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;
}
}