Max*_*hen 5 c# authorize-attribute asp.net-mvc-filters asp.net-web-api2
CustomAuthorizeAttribute我的Web Api项目中定义了默认值.
config.Filters.Add(new CustomAuthorizeAttribute());
Run Code Online (Sandbox Code Playgroud)
但是我有一个特殊的控制器,我想使用一个SpecialAuthorizeAttribute.
[SpecialAuthorize]
public class MySpecialController : ApiController
Run Code Online (Sandbox Code Playgroud)
在Asp.Net vNext中,我们有一个新属性来覆盖默认过滤器,但是如何让它在Web Api 2中工作呢?
编辑1:
一种可能的(但不是理想的)解决方案是使CustomAuthorizeAttribute检查Controller或Action范围内是否有另一个AuthorizeAttribute.在我的情况下,我只有SpecialAuthorizeAttribute所以:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1263 次 |
| 最近记录: |