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());
}
}
如果我遗漏了什么,请帮忙。
最佳答案
- 看起来您正在使用 MVC 过滤器而不是 Web API 过滤器。它可以在示例中检测到,因为它使用了
HttpContextBase
。而是使用System.Web.Http.Filters
命名空间中的过滤器。 - 您需要覆盖 Web API 过滤器上的 OnAuthorization 或 OnAuthorizationAsync。
- 您不需要注册一个全局过滤器并用它装饰您的 Controller 。注册它将使其在所有 Controller 上运行。
Web API 过滤器代码: https://github.com/aspnetwebstack/aspnetwebstack/blob/master/src/System.Web.Http/Filters/AuthorizationFilterAttribute.cs
关于c# - 自定义授权属性在 WebAPI 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23339002/