【问题标题】:Bitwise OR as a input parameter in custom attribute按位或作为自定义属性中的输入参数
【发布时间】:2018-12-04 02:04:51
【问题描述】:

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

[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.
        }
    }
}

提前致谢。

【问题讨论】:

    标签: c# asp.net-mvc bitwise-or


    【解决方案1】:

    像这样定义你的 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}");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-19
      • 2012-03-09
      • 1970-01-01
      • 2013-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多