你被以下事实弄糊涂了
AuthorizeAttribute
实现两个
Attribute
和
IAuthorizationFilter
。您需要做的是进行全球注册
IAuthorizationFilter
并使用它来确定
CustomAuthorizeAttribute
存在于操作或控制器上。然后您可以确定哪个优先于另一个。
CustomAuthorizeAttribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CustomAuthorizeAttribute : Attribute
{
public eUserRole CustomRoles { get; set; } = eUserRole.Administrator;
}
CustomAuthorization筛选器
在这里,我们通过子类化来保存一些步骤
授权属性
,但我们不打算
属性
实际上,只有一个全局注册的过滤器。
我们的过滤器包含反射代码来确定
CustomAuthorize
如果两者都已定义,则属性优先。这是为了使动作方法覆盖控制器而设置的,但如果需要,可以使逻辑更加复杂。
public class CustomAuthorizationFilter : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
if (base.IsAuthorized(actionContext))
{
var authorizeAttribute = GetAuthorizeAttribute(actionContext.ActionDescriptor);
if (authorizeAttribute == null)
return true;
var roles = authorizeAttribute.CustomRoles;
}
return false;
}
private CustomAuthorizeAttribute GetAuthorizeAttribute(HttpActionDescriptor actionDescriptor)
{
CustomAuthorizeAttribute result = actionDescriptor
.GetCustomAttributes<CustomAuthorizeAttribute>()
.FirstOrDefault();
if (result != null)
return result;
result = actionDescriptor
.ControllerDescriptor
.GetCustomAttributes<CustomAuthorizeAttribute>()
.FirstOrDefault();
return result;
}
}
用法
我们全局注册过滤器。对于每个请求,
CustomAuthorizationFilter
扫描请求中的操作和控制器,以查看该属性是否存在。如果是,则运行逻辑。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.Filters.Add(new CustomAuthorizationFilter());
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
注:
从技术上讲,您可以将它们保持在同一个类中,但如果将它们划分为
实际上是
而不是创建一个执行多个作业(属性和过滤器)的单个类。
参考号:
Passive Attributes