看着AttributeUsage
的属性Authorize
属性 https://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute(v=vs.118).aspx ;
[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Method,
Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
Inherited= true
意味着用该属性修饰的类的子类可以继承该属性。
AllowMultiple=true
意味着该属性可以在同一实体上多次放置。
通过继承的属性并允许使用相同的属性,您的SalesController
可以被认为是
[Authorize(Roles = "Sales")]
[Authorize(Roles = "Employee")]
[Authorize(Roles = "Admin")]
[Authorize(Roles = "Owner")]
public abstract class SalesController:EmployeeController { }
您可以使用此代码在运行时进行测试。
var a = typeof(SalesController).GetCustomAttributes(true).ToArray();
第一个问题,将Owner
, Admin
and Employee
角色可以访问SalesController
?
继承的属性是分离的,因此它们独立应用。供一个用户访问SalesController
,用户必须拥有所有角色(owner
,admin
,employee
and sales
)不是其中之一。
查看之间的区别
[Authorize(Roles = "Sales")]
[Authorize(Roles = "Employee")]
[Authorize(Roles = "Admin")]
[Authorize(Roles = "Owner")]
public abstract class SalesController:EmployeeController { }
and
[Authorize(Roles = "Owner,Admin,Employee,Sales")]
public abstract class SalesController:EmployeeController { }
第二个问题: 如果你走[Authorize]
具有相同逻辑的未注释AccountController
is like
[Authorize(Roles = "Owner")]
[Authorize]
public class AccountController:ControllerAuthorities{}
因此它不会覆盖继承的权限,只是创建授权属性的多次使用,因为允许多次使用Authorize
属性。如果AllowMultiple
were false
in Authorize
属性定义然后派生类可以覆盖基类中的属性。