3

如何在我的自定义属性中使用按位或运算传递多个参数,与方法或类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.
        }
    }
}

提前致谢。

4

1 回答 1

5

像这样定义您的 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}");
于 2018-12-04T02:16:43.870 回答