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

标签 c# asp.net-mvc asp.net-web-api filter authorization

 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. 看起来您正在使用 MVC 过滤器而不是 Web API 过滤器。它可以在示例中检测到,因为它使用了 HttpContextBase。而是使用 System.Web.Http.Filters 命名空间中的过滤器。
  2. 您需要覆盖 Web API 过滤器上的 OnAuthorization OnAuthorizationAsync。
  3. 您不需要注册一个全局过滤器并用它装饰您的 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/

相关文章:

c# - 添加RequiredFieldValidator运行时

c# - Blazor 在 EditForm 中绑定(bind) List<string>

javascript - 使用 jquery 管理复选框并将这些值发送到 Controller 中

asp.net-web-api - 查询 odata 中的嵌套导航属性

c# - 如何使用 webapi 2 将数据从 AuthorizeAttribute 传递到 Controller ?

c# - SVM 可以增量学习吗?

c# - DELETE 方法似乎什么都不做

asp.net-mvc - .Net 4内存缓存类和用户 session

javascript - 不破坏 JavaScript IntelliSense 的 ASP.NET MVC 相对路径?

c# - 带 *.js 的 URL 的 WebApi 属性路由