我为 NancyFX 做了我的自定义 404 处理程序,它工作正常,但有一个问题。问题是它甚至会覆盖那些我想发送 404 代码但带有我的自定义消息的请求,例如“找不到用户”。
处理程序
public class NotFoundHandler : IStatusCodeHandler
{
public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
{
if (statusCode == HttpStatusCode.NotFound)
{
// How to check here if the url actually exists?
// I don't want every 404 request to be the same
// I want to send custom 404 with Response.AsJson(object, HttpStatusCode.NotFound)
return true;
}
return false;
}
public void Handle(HttpStatusCode statusCode, NancyContext context)
{
context.Response = new TextResponse(JsonConvert.SerializeObject(new { Message = "Resource not found" }, Formatting.Indented))
{
StatusCode = statusCode,
ContentType = "application/json"
};
}
}
问题
Get["/"] = _ =>
{
// This will not show "User not found", instead it will be overriden and it will show "Resource not found"
return Response.AsJson(new { Message = "User not found" }, HttpStatusCode.NotFound);
};