c# - 在 [Authorize(Roles)] 上使用枚举 [Flags] 和按位运算符

标签 c# enums

我正在构建一个 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/

相关文章:

C# 在处理字符串时使用正则表达式

c# - 使 WPF TextBlock 只增长而不收缩?

java - 枚举类如何扩展另一个外部库类?

c# - 翻译 "Multilanguage"枚举 javascript/c#

c - 为什么有时 linux 内核中枚举的第一个成员用 0 初始化

django - Postgres : add description of an ENUM value?

c# - ListView 分组和排序

c# - MVC 4 EmailAddress - String EditorTemplate 未被使用

oop - 将Dart枚举放入类或包导出文件中

c# - ActiveX 的 .NET 使用者抛出 TargetParameterCountException