自定义授权属性在WebAPI中不起作用

public class CustomAuthorizeAttribute : AuthorizationFilterAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { return true;// if my current user is authorised } } 

上面是我的CustomAuthorizeAttribute类和

 [CustomAuthorize] // both [CustomAuthorize] and [CustomAuthorizeAttribute ] I tried public class ProfileController : ApiController { //My Code.. } 

当我打电话的时候

 http://localhost:1142/api/Profile 

它没有触发CustomAuthorizeAttribute

我的FilterConfig类的内容如下所示

 public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new CustomAuthorizeAttribute()); } } 

如果我错过了什么请帮忙。

  1. 看起来您使用的是MVCfilter而不是Web APIfilter。 它可以在样本中检测到,因为它使用HttpContextBase 。 而是使用System.Web.Http.Filters命名空间中的filter。
  2. 您需要在Web APIfilter上覆盖OnAuthorization OnAuthorizationAsync。
  3. 您无需注册全局filter并使用它来装饰控制器。 注册它将使其运行所有控制器。

Web APIfilter代码: https : //aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Http/Filters/AuthorizationFilterAttribute.cs

试试这个。

 public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) { return true; } } 

你的自定义属性应该inheritance自System.Web.Http.Filters.AuthorizationFilterAttribute

它看起来应该是这样的

 using System.Web.Http.Controllers; using System.Web.Http.Filters; public class CustomAuthorizeAttribute : System.Web.Http.Filters.AuthorizationFilterAttribute { public override bool AllowMultiple { get { return false; } } public override void OnAuthorization(HttpActionContext actionContext) { //Perform your logic here base.OnAuthorization(actionContext); } }