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