带有点网 6 中角色名称的自定义错误的角色基础身份验证

Role base authentication with custom error with role name in dot net 6

我在控制器的方法顶部使用下面的行进行基于角色的身份验证

[HttpGet("getAll"), Authorize(Roles = "GetAll")]

当用户无权访问此角色时,我想告诉用户您需要“GetAll”角色

可以吗?

你可以在方法中查看角色,像这样:

[HttpGet("getAll"), Authorize]
        public async Task<IActionResult> GetAll()
        {
            if (!Roles.Any(r => r == "getAll"))
            {
                return Unauthorized("Pass the role name");
            }

            return Ok();
        }

角色 包含用户访问的角色