如何更改 Web Api Core 未经授权的行为

Sib*_*Guy 6 asp.net-web-api asp.net-identity asp.net-identity-3 asp.net-core

ASP.NET Web Api Core未授权请求的默认行为是发送401/403 error空内容。我想通过指定某种指定错误的 Json 响应来更改它。

但是我很难找到一个合适的地方来引入这些变化。官方文档没有帮助(阅读全部内容)。我猜测可能是我可以UnathorizedException在我的异常过滤器/中间件中捕获,但它没有解决(我猜它在授权级别得到处理,甚至根本没有抛出)。

所以我的问题是如何在未经授权的请求的情况下自定义响应行为。

bit*_*bit 0

使用 .Net Core 3(或者也可能更早),您可以编写一个中间件来检查 context.Response 的状态是否为 40x,然后返回自定义对象。以下是我的大致做法:

if (context.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
{
 var result = new MyStandardApiResponseDto
 {
  Error = new MyErrorDto
   {
    Title = "Unauthorized",
     Messages = new List<string> { "You are not authorized to access the resource. Please login again." },
   },
  Result = null
 };
 await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
}
Run Code Online (Sandbox Code Playgroud)