3

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

1 に答える 1

2

IStatusCodeHandler実装で処理する応答を決定します。現時点では、コンテキストを追加せずに、ステータス コード自体を確認しているだけです。(たとえば)できることcontext.Responseは、タイプであるなど、特定の基準を満たすレスポンスが含まれていない場合にのみ上書きすることですJsonResponse

    if(!(context.Response Is JsonResponse))
    {
            context.Response = new TextResponse(JsonConvert.SerializeObject(new { Message = "Resource not found" }, Formatting.Indented))
            {
                StatusCode = statusCode,
                ContentType = "application/json"
            };
    }

full にアクセスできるので、 andNancyContext全体にもアクセスできます(これは、リクエスト パイプライン内のルートまたは何かによって返されたものです)。さらに制御が必要な場合は、任意のメタデータを追加できます。RequestResponseNancyContext.Items

お役に立てれば

于 2013-08-25T15:22:35.067 に答える