虽然我会用 基于资源的授权 正如我评论的那样,有一种方法可以实现您的目标:
首先创建一个自定义属性:
public class AgeAuthorizeAttribute : Attribute { public int Age{ get; set; } public AgeAuthorizeAttribute(int age) { Age = age; } }
然后编写过滤器提供程序:
public class CustomFilterProvider : IFilterProvider { public int Order { get { return 0; } } public void OnProvidersExecuted(FilterProviderContext context) { } public void OnProvidersExecuting(FilterProviderContext context) { var ctrl = context.ActionContext.ActionDescriptor as ControllerActionDescriptor; var ageAttr = ctrl.MethodInfo.GetCustomAttribute<AgeAuthorizeAttribute>(); if (ageAttr == null) { ageAttr = ctrl.ControllerTypeInfo.GetCustomAttribute<AgeAuthorizeAttribute>(); } if (ageAttr != null) { var policy = new AuthorizationPolicyBuilder() .AddRequirements(new MinimumAgeRequirement(ageAttr.Age)) .Build(); var filter = new AuthorizeFilter(policy); context.Results.Add(new FilterItem(new FilterDescriptor(filter, FilterScope.Action), filter)); } } }
最后注册过滤提供商:
services.TryAddEnumerable(ServiceDescriptor.Singleton<IFilterProvider, CustomFilterProvider>());
并使用它
[AgeAuthorize(21)] public IActionResult SomeAction() ... or [AgeAuthorize(21)] public class AlcoholPurchaseRequirementsController : Controller
ps:未经测试