按位或作为自定义属性中的输入参数

Bitwise OR as a input parameter in custom attribute

如何在我的自定义 FeatureAuthorize 属性中使用按位或运算传递多个参数,同样 AttributeUsage 支持 AttributeTarget 作为方法或 class.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]

以下是我想要实现的示例,提供的任何汇款或收款方法功能都应该可以访问。

[FeatureAuthorize(Feature = EnumFeature.SendMoney | EnumFeature.ReceiveMoney)]
public ActionResult SendOrReceiveMoney(int? id, EnumBankAccountType? type)
{
 // My code
}

FeatureAuthorize 属性的正文如下。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class FeatureAuthorizeAttribute : AuthorizeAttribute
{
    public EnumFeature Feature { get; set; }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!IsFeatureAllowed(Feature)) // Verification in database.
        {
             // Redirection to not authorize page.
        }
    }
}

提前致谢。

像这样定义您的 EnumFeature:

[Flags]
public enum EnumFeature {
  Send = 1,
  Received = 2,
  BalanceEnquery = 4,
  CloseAccount = 8
}

注意每个后续枚举值如何是 2 的下一个最高幂。在您的 auth 属性中,您可以使用 Enum.HasFlag 查看是否设置了标志。但是您可能希望确保不会通过使用其他按位运算来设置其他标志。

像这样

var acceptable = EnumFeature.Send | EnumFeature.Received;
var input = EnumFeature.Send | EnumFeature. CloseAccount;

// Negate the values which are acceptable, then we'll AND with the input; if that result is 0, then we didn't get any invalid flags set.  We can then use HasFlag to see if we got Send or Received
var clearAcceptable = ~acceptable;
Console.WriteLine($"Input valid: {(input & clearAcceptable) == 0}");