如何通过自定义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.
}
}
}
谢谢。
答案 0 :(得分: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}");