首页 新闻 会员 周边

ASP.NET Core Middleware 中响应 401 Unauthorized 错误的最优雅姿势

0
悬赏园豆:50 [已解决问题] 解决于 2020-03-05 14:42

请问在 ASP.NET Core 中间件中响应 401 Unauthorized 错误的最优雅姿势是什么?

如果是 Controller Action ,可以用 return Unauthorized(); ,在 middleware 该用什么姿势呢?

dudu的主页 dudu | 高人七级 | 园豆:31003
提问于:2020-03-05 13:47
< >
分享
最佳答案
0

在这篇博文 Elegant way of producing HTTP responses in ASP.NET Core outside of MVC controllers 中找到了优雅姿势。

app.Use(async (context, next) =>
{
    if (!await userService.IsUserInRoleAsync("xxx", userId))
    {
        await context.Unauthorized("401 Unauthorized");
    }
    else
    {
        await next.Invoke();
    }
});

注:需要安装 nuget 包 WebApiContrib.Core 。

dudu | 高人七级 |园豆:31003 | 2020-03-05 14:42
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册