I want to respond with a JSON response model when a 401 and 403 occur. For example:
HTTP 401
{
"message": "Authentication failed. The request must include a valid and non-expired bearer token in the Authorization header."
}
I am using middleware (as suggested in this answer) to intercept 404s and it works great, but it is not the case with 401 or 403s. Here is the 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);
}
});
When placed BELOW app.UseJwtBearerAuthentication(..)
in Startup.Configure(..)
, it seems to be completely ignored and a normal 401 is returned.
When placed ABOVE app.UseJwtBearerAuthentication(..)
in Startup.Configure(..)
, then the following exception is thrown:
Connection id "0HKT7SUBPLHEM": An unhandled exception was thrown by the application. System.InvalidOperationException: Headers are read-only, response has already started. at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameHeaders.Microsoft.AspNetCore.Http.IHeaderDictionary.set_Item(String key, StringValues value) at Microsoft.AspNetCore.Http.Internal.DefaultHttpResponse.set_ContentType(String value) at MyProject.Api.Startup.<b__12_0>d.MoveNext() in Startup.cs