从控制器获取 [Authorize] 数据

Get [Authorize] data from controller

我有代码:

[Authorize(Roles = "SuperAdministrators")]
public class ButtonStyleController : ControllerBase
{

其他地方:

[Authorize(Roles = "SuperAdministrators,CompanyAdministrators")]
public class BankController : ControllerBase
{

甚至:

[Authorize(Roles = "CompanyAdministrators")]
public class DriverController : ApiControllerBase
{

我需要在代码中检查当前控制器允许哪些角色。可能吗?

您可以使用以下代码从 class 获取 AuthorizeAttribute 类型的属性,然后访问角色 属性。

AuthorizeAttribute currentAuthorizeAttribute = (AuthorizeAttribute)Attribute.GetCustomAttribute(typeof(DriverController), typeof(AuthorizeAttribute));
string roles = currentAuthorizeAttribute.Roles;