我正在构建一个 ASP.NET MVC 5 应用程序,并遵循此 SO post 中的示例将 [Flags]
应用于 enum
:
[Flags]
public enum Role
{
User = 1,
Finance = 2,
Management = 4,
SystemAdmin = 8
}
请注意,[Flags]
属性为我们提供了一种将多个值作为一个逗号分隔字符串获取的好方法:
var roles = (Constants.Role.SystemAdmin | Constants.Role.Management).ToString();
// "SystemAdmin, Management"
枚举值将在 Controller 和操作的 [Authorize]
属性中使用,例如:
[Authorize(Roles = (Constants.Role.SystemAdmin | Constants.Role.Management).ToString())]
public class SomeController : Controller
{ ... }
但是,上述属性会产生此错误:
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
为什么我可以使用 .ToString()
方法并在代码中获取枚举的 CSV 而不是在 [Authorize]
属性中使用相同的语句?
最佳答案
因为属性是元数据,所以它们有一个限制,即它们的初始化必须是常量。正如你的错误所说:
An attribute argument must be a constant expression
ToString()
是一个方法调用,因此不能保证是常量。这就是您可以使用它的原因。
要解决这个问题,您可能能够继承 Authorize
并执行如下操作:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
private Role roleEnum;
public Role RoleEnum
{
get { return roleEnum; }
set { roleEnum = value; base.Roles = value.ToString(); }
}
}
你可以这样使用:
[MyAuthorize(RoleEnum = Constants.Role.SystemAdmin | Constants.Role.Management)]
^ 不需要 ToString()
关于c# - 在 [Authorize(Roles)] 上使用枚举 [Flags] 和按位运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44656002/