C# 用另一个替代授权筛选器
我在Web Api项目中定义了默认的C# 用另一个替代授权筛选器,c#,asp.net-web-api2,authorize-attribute,asp.net-mvc-filters,C#,Asp.net Web Api2,Authorize Attribute,Asp.net Mvc Filters,我在Web Api项目中定义了默认的CustomAuthorizationAttribute。 但是,我有一个特殊的控制器,我想在其中使用SpecialAuthorizeAttribute。 在Asp.NETVNEXT中,我们有一个新的属性来覆盖默认过滤器,但是如何使它在WebAPI2中工作呢 编辑1: 一种可能的(但不是理想的)解决方案是让CustomAuthorizeAttribute检查控制器或操作的作用域中是否有另一个AuthorizeAttribute。就我而言,我只有Specia
CustomAuthorizationAttribute
。
但是,我有一个特殊的控制器,我想在其中使用SpecialAuthorizeAttribute
。
在Asp.NETVNEXT中,我们有一个新的属性来覆盖默认过滤器,但是如何使它在WebAPI2中工作呢
编辑1:
一种可能的(但不是理想的)解决方案是让CustomAuthorizeAttribute检查控制器或操作的作用域中是否有另一个AuthorizeAttribute。就我而言,我只有SpecialAuthorizeAttribute,因此:
公共类CustomAuthorizeAttribute:AuthorizeAttribute
{
授权时的公共覆盖无效(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if(actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes().Any()| | actionContext.ActionDescriptor.GetCustomAttributes().Any())
{
返回;
}
基于授权(actionContext);
}
公共重写System.Threading.Tasks.Task OnAuthorizationAsync(System.Web.Http.Controllers.HttpActionContext actionContext,System.Threading.CancellationToken CancellationToken)
{
返回base.OnAuthorizationAsync(actionContext,cancellationToken);
}
}
您可以使用。
可以使用此属性来抑制全局身份验证筛选器 OverrideAuthorization属性(在ASP.NET Web API 2中)完全适合您的需求。您可以在文章中简单地找到它的用法和用途。您可以将CustomAuthorization属性应用于其他控制器,而不是通过将其添加到配置中使其成为全局属性。这意味着您需要装饰每个控制器,但它可能更清楚地定义了您实际在做什么。
config.Filters.Add(new CustomAuthorizeAttribute());
[SpecialAuthorize]
public class MySpecialController : ApiController
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<SpecialAuthorizeAttribute>().Any() || actionContext.ActionDescriptor.GetCustomAttributes<SpecialAuthorizeAttribute>().Any())
{
return;
}
base.OnAuthorization(actionContext);
}
public override System.Threading.Tasks.Task OnAuthorizationAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
{
return base.OnAuthorizationAsync(actionContext, cancellationToken);
}
}