是否可以通过IAuthorizationHandler访问自定义属性属性?
我具有自定义授权属性
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public VipAuthorize VipAuthorize { get; set; } = VipAuthorize.Ignore;
public CustomAuthorizeAttribute(VipAuthorize vipAuthorize, params
UserRoleEnum[] roles) : base()
{
Roles = string.Join(",", roles).ToUpper();
VipAuthorize = VipAuthorize;
}
public CustomAuthorizeAttribute(params UserRoleEnum[] roles) : base()
{
Roles = string.Join(",", roles).ToUpper();
}
}
我也有授权处理程序
public class CustomAuthorizationHandler : IAuthorizationHandler
{
public Task HandleAsync(AuthorizationHandlerContext context)
{
if (context.Resource != null)
{
var httpContext = ((AuthorizationFilterContext)context.Resource).HttpContext;
var distributedCache = (IDistributedCache)httpContext.RequestServices.GetService(typeof(IDistributedCache));
var userIdentifier = context.User.Claims.FirstOrDefault(x => x.Type == GlobalData.CustomClaimNames.UserId);
var userId = userIdentifier.Value;
var userAuthCacheStr = distributedCache.GetString(GlobalData.CacheGlobalKeys.UserId(userId));
var userQuickModelCahce = JsonConvert.DeserializeObject<UserQuickModelCache>(userAuthCacheStr);
if (userQuickModelCahce.UserType == AuthUserType.Client && userQuickModelCahce.SubscriptionExpired)
{
context.Fail();
throw new CustomException(GlobalData.Translations.Keys.SubscriptionExpired, HttpStatusCode.Redirect);
}
var roles = context.PendingRequirements.Where(x => x.GetType() == typeof(RolesAuthorizationRequirement))
.SelectMany(x => ((RolesAuthorizationRequirement)x).AllowedRoles.Select(r => r.ToUpper())).ToList();
if (roles?.Count > 0)
{
if (!roles.Contains("AnyRole"))
{
context.Fail();
throw new CustomException(GlobalData.Translations.Keys.NotAuthorized, HttpStatusCode.Unauthorized);
}
}
}
context.Succeed(context.Requirements.FirstOrDefault());
return Task.CompletedTask;
}
}
在此处理程序中,我想从CustomAuthorizeAttribute访问VipAuthorize属性。这样,我将能够在需要的地方忽略VIP用户验证。
这是我的用法:
[HttpPost]
[CustomAuthorize(VipAuthorize.Ignore, UserRoleEnum.Client)]
public async Task<IActionResult> Add()
{
var item = await _accounttransactionService.Create();
await _accounttransactionService.Commit();
return Ok(item.ToDto<AccountTransactionDto>());
}