【问题标题】:How to change Web Api Core unauthorized behavior如何更改 Web Api Core 未经授权的行为
【发布时间】:2017-06-15 22:44:09
【问题描述】:

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

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

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

【问题讨论】:

  • 查看app.UseStatusCodePagesWithRedirectsapp.UseStatusCodePages等扩展方法
  • https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie 转到此...它可能会有所帮助
  • @Developer,它似乎是特定于 MVC,而不是 Web Api
  • asp.net-core有这样的区别吗?你的认证机制是什么?
  • @Developer,我使用令牌身份验证。顺便说一下,这里的代码:github.com/alexidsa/absenceapi

标签: asp.net-web-api asp.net-core asp.net-identity asp.net-identity-3


【解决方案1】:

使用 .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));
}

【讨论】:

    猜你喜欢
    • 2020-02-11
    • 1970-01-01
    • 2017-11-09
    • 2020-03-04
    • 2014-10-03
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    相关资源
    最近更新 更多