2012-09-06 15 views
0

我有一個MVC Web Api控制器,它在類級使用[Authorize]屬性。這使得所有的API方法都需要授權,但是我想創建一個名爲[ApiPublic]的屬性來覆蓋[Authorize]屬性。對於正常的MVC控制器,描述了類似的技術here如何覆蓋MVC Web API中的[Authorize]屬性?

我試圖創建基於System.Web.Http.AuthorizeAttribute,但沒有被覆蓋的事件被稱爲如果我把它放在一個具有[授權]在類級別的API方法的AuthorizeAttribute。任何人都有一個想法如何重寫Web API的授權?

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] 
public class ApiPublicAttribute : AuthorizeAttribute 
{ 
    protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext) 
    { 
     base.HandleUnauthorizedRequest(actionContext); 
    } 

    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) 
    { 
     base.OnAuthorization(actionContext); 
    } 

    protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) 
    { 
     return true; 
    } 
} 

回答

8

我可以推薦你使用[AllowAnonymous]嗎?

你可以在任何方法上對此進行歸因,它會覆蓋你在類級別指定的Authorize屬性,從而避免編寫自己的屬性。