Benutzerdefiniertes 401- und 403-Antwortmodell mit UseJwtBearerAuthentication-Middleware

Ich möchte mit einem JSON-Antwortmodell antworten, wenn 401 und 403 auftreten. Beispielsweise

HTTP 401
{
  "message": "Authentication failed. The request must include a valid and non-expired bearer token in the Authorization header."
}

Ich verwende Middleware (wie in @ vorgeschlagediese Antwort) 404s abfangen und es funktioniert super, aber das ist bei 401 oder 403s nicht der Fall. Hier ist die Middleware:

app.Use(async (context, next) =>
{
    await next();
    if (context.Response.StatusCode == 401)
    {
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync(JsonConvert.SerializeObject(UnauthorizedModel.Create(), SerializerSettings), Encoding.UTF8);
    }
});

Wenn UNTEN @ platzieapp.UseJwtBearerAuthentication(..) imStartup.Configure(..), es scheint völlig ignoriert zu werden und ein normaler 401 wird zurückgegeben.

Wenn ÜBER @ platzieapp.UseJwtBearerAuthentication(..) imStartup.Configure(..), dann wird die folgende Ausnahme ausgelöst:

Connection id "0HKT7SUBPLHEM": Die Anwendung hat eine nicht behandelte Ausnahme ausgelöst. System.InvalidOperationException: Header sind schreibgeschützt, die Antwort wurde bereits gestartet. um Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameHeaders.Microsoft.AspNetCore.Http.IHeaderDictionary.set_Item (String key, StringValues value) um Microsoft.AspNetCore.Http.Internal.DefaultHttpResponse.set_Content (MyType). Api.Startup. <B__12_0> d.MoveNext () in Startup.cs

Antworten auf die Frage(4)

Ihre Antwort auf die Frage