自定义授权属性不工作的WebAPI [英] Custom authorization attribute not working in WebAPI

查看:310
本文介绍了自定义授权属性不工作的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 公共类CustomAuthorizeAttribute:AuthorizationFilterAttribute
 {
    保护覆盖布尔AuthorizeCore(HttpContextBase的HttpContext)
    {
       返回true; //如果我当前用户被授权
    }
 }

以上是我CustomAuthorizeAttribute类

  [CustomAuthorize] //两者[CustomAuthorize]和[CustomAuthorizeAttribute]我试着
公共类ProfileController可:ApiController
{
   //我的code ..
}

当我打电话

 的http://本地主机:1142 / API /简介

据不点火 CustomAuthorizeAttribute

在更多我的一个FilterConfig类是类似于以下

 公共类一个FilterConfig
{
    公共静态无效RegisterGlobalFilters(GlobalFilterCollection过滤器)
    {
        filters.Add(新CustomAuthorizeAttribute());
    }
}

如果我错过了什么,请帮助。


解决方案

  1. 看起来像您正在使用MVC像过滤器,而不是一个网页API过滤器。需要注意的HttpContextBase。使用

  2. 您需要重写OnAuthorization或OnAuthorizationAsync上的Web API过滤器。

  3. 您并不需要注册一个全球性的过滤器,并用它装点您的控制器。注册它将使运行所有控制器。

网页API过滤器code:
<一href=\"https://aspnetwebstack.$c$cplex.com/SourceControl/latest#src/System.Web.Http/Filters/AuthorizationFilterAttribute.cs\">https://aspnetwebstack.$c$cplex.com/SourceControl/latest#src/System.Web.Http/Filters/AuthorizationFilterAttribute.cs

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

Above is my CustomAuthorizeAttribute Class and

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

When I'm calling

http://localhost:1142/api/Profile 

It is not firing CustomAuthorizeAttribute

More over My FilterConfig class is look like below

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

Please help if I miss something.

解决方案

  1. Looks like you are using an MVC like filter and not a Web API filter. Note the usage of HttpContextBase.
  2. You need to override OnAuthorization or OnAuthorizationAsync on the Web API filter.
  3. You don't need to register a global filter and decorate your controller with it. Registering it will make it run for all controllers.

Web API filter code: https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Http/Filters/AuthorizationFilterAttribute.cs

这篇关于自定义授权属性不工作的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆