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());
}
}
如果我错过了什么,请帮助。
答案 0 :(得分:21)
HttpContextBase
。而是使用System.Web.Http.Filters
命名空间中的过滤器。Web API过滤器代码: https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Http/Filters/AuthorizationFilterAttribute.cs
答案 1 :(得分:11)
你的自定义属性应该继承自 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);
}
}
答案 2 :(得分:9)
试试这个。
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
{
return true;
}
}
答案 3 :(得分:0)
要添加从System.Web.Http.Filters.AuthorizationFilterAttribute
继承的其他答案,我将其放入我的OnAuthorization
方法中以确保用户已登录:
if (!actionContext.RequestContext.Principal.Identity.IsAuthenticated)
{
// or whatever sort you want to do to end the execution of the request
throw new HttpException(403, "Forbidden");
}