相关疑难解决方法(0)

使用UseJwtBearerAuthentication中间件的自定义401和403响应模型

当401和403出现时,我想用JSON响应模型做出响应.例如:

HTTP 401
{
  "message": "Authentication failed. The request must include a valid and non-expired bearer token in the Authorization header."
}
Run Code Online (Sandbox Code Playgroud)

我正在使用中间件(如本答案中所建议的)拦截404并且它工作得很好,但401或403并非如此.这是中间件:

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

当置于下方app.UseJwtBearerAuthentication(..)Startup.Configure(..),它似乎被完全忽略并返回正常的401.

当置于ABOVE app.UseJwtBearerAuthentication(..)中时Startup.Configure(..),将抛出以下异常:

连接标识"0HKT7SUBPLHEM":应用程序抛出了未处理的异常.System.InvalidOperationException:标头是只读的,响应已经开始.在MicrosoftPro.AspNetCore.Server.Kestrel.Internal.Http.FrameHeaders.Microsoft.AspNetCore.Http.IHeaderDictionary.set_Item(String key,StringValues value),位于MyProject的Microsoft.AspNetCore.Http.Internal.DefaultHttpResponse.set_ContentType(String value). Startup.cs中的Api.Startup.<b__12_0> d.MoveNext()

asp.net-core-mvc asp.net-core asp.net-core-1.0

10
推荐指数
2
解决办法
5906
查看次数