[英]Bitwise OR as a input parameter in custom attribute
How to pass multiple parameters with bitwise OR operation in my custom FeatureAuthorize
attribute, same way AttributeUsage
supports AttributeTarget
as a method or class. 如何在我的自定义
FeatureAuthorize
属性中使用按位OR运算传递多个参数,同样, AttributeUsage
支持AttributeTarget
作为方法或类。
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
Below are the example that I want to achieve, any of the feature provided either send money or receive money method should be accessible. 以下是我想要实现的示例,提供的任何功能,无论是发送钱还是收款方法都应该是可访问的。
[FeatureAuthorize(Feature = EnumFeature.SendMoney | EnumFeature.ReceiveMoney)]
public ActionResult SendOrReceiveMoney(int? id, EnumBankAccountType? type)
{
// My code
}
Body of the FeatureAuthorize Attribute is like. 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.
}
}
}
Thanks in advance. 提前致谢。
Define your EnumFeature like this: 像这样定义您的EnumFeature:
[Flags]
public enum EnumFeature {
Send = 1,
Received = 2,
BalanceEnquery = 4,
CloseAccount = 8
}
Notice how each subsequent enum value is the next highest power of 2. In your auth attribute, you can use Enum.HasFlag to see if a flag is set. 注意每个后续枚举值是否是2的下一个最高幂。在auth属性中,可以使用Enum.HasFlag查看是否设置了标志。 But you'll probably want to ensure that other flags aren't set by using other bitwise operations.
但是您可能希望确保不使用其他按位操作设置其他标志。
Something like this 像这样的东西
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}");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.