Hic*_*cup 3 c# asp.net-mvc bitwise-or
如何在我的自定义FeatureAuthorize属性中使用按位OR运算传递多个参数,同样AttributeUsage支持AttributeTarget方法或类.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
Run Code Online (Sandbox Code Playgroud)
以下是我想要实现的示例,提供的任何功能,无论是发送钱还是收款方法都应该是可访问的.
[FeatureAuthorize(Feature = EnumFeature.SendMoney | EnumFeature.ReceiveMoney)]
public ActionResult SendOrReceiveMoney(int? id, EnumBankAccountType? type)
{
// My code
}
Run Code Online (Sandbox Code Playgroud)
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.
}
}
}
Run Code Online (Sandbox Code Playgroud)
提前致谢.
像这样定义您的EnumFeature:
[Flags]
public enum EnumFeature {
Send = 1,
Received = 2,
BalanceEnquery = 4,
CloseAccount = 8
}
Run Code Online (Sandbox Code Playgroud)
注意每个后续枚举值是否是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}");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64 次 |
| 最近记录: |