我需要在Nancy中显示我的404错误页面,如此
if (ErrorCode == 404)
{
return View["404.html"];
}
怎么做?
答案 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;
}
}