2012-12-14 178 views
18

我正在使用asp.net WebAPI,我需要創建一個自定義ActionFilter,它可以快速檢查請求URI的用戶是否應該實際上能夠獲取數據。返回狀態代碼未經授權在WebAPI中定製IActionFilter

他們已被授權通過基本身份驗證使用Web服務,並且他們的角色已通過自定義角色提供者進行驗證。

我需要做的最後一件事是檢查他們是否有權查看他們請求的數據並使用其URI中的參數。

這裏是我的代碼:

public class AccessActionFilter : FilterAttribute, IActionFilter 
    { 

     public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken, Func<System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>> continuation) 
     { 

      var result = //code to see if they have permission returns either 0 or 1 

      if (result==0) { 
       throw new ArgumentException("You do not have access to this resource"); 
      } 
      return continuation(); 
     } 
    } 

目前,我只是把它不是我想要的,我寧願回到System.Net.HttpStatusCode.Unauthorized一個錯誤,但我對我重寫方法有點惱火,我做不完全理解它。

我該如何去解決這個問題?

+0

由於授權不只是失蹤,而是身份已經提供,但用戶不能訪問,適當的HTTP響應是403禁止的。 –

回答

27

你可能最好堅持一個例外,但使用HttpResponseException也會返回一個Http狀態碼。

throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)); 

好問題here這個。

p.s.

它可以更簡單/清潔劑來實現ActionFilterAttribute

public class AccessActionFilter : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(HttpActionContext actionContext) 
    { 
     var result = //code to see if they have permission returns either 0 or 1 

     if (result==0) 
     { 
      throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)); 
     } 
     base.OnActionExecuting(actionContext); 
    } 

}

+2

這違反了HTTP 1.1。它說[401錯誤](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)必須提供一個「WWW-Authenticate」來指示可接受的方案。 'ApiController.Unauthorized'有一個參數。幸運的是,403 Forbidden這不是問題。 –

+0

拋出異常是很昂貴的,所以這難道不會通過發送很多無效嘗試來攻擊服務器,並且會從拋出的HttpResponseExceptions的開銷中加載服務器嗎?或者,來自多個請求的帶寬無論如何都是瓶頸,所以它不會有重大影響? – BornToCode

+0

@BornToCode像這樣的所有異常將在HttpControllerDispatcher(http://chimera.labs.oreilly.com/books/1234000001708/ch12.html#_apicontroller_processing_model)中捕獲一個相當簡單的嘗試catch,專門尋找HttpResponseException - 我不是確定它們真的很可能是多麼昂貴 - 我一如既往建議在測試中測試它並測量 - 如果差異會成爲問題,我會感到驚訝 - 請訪問http://stackoverflow.com/questions/ 891217/how-expensive-are-exceptions-in-c以及判斷異常是否確實是「昂貴的」 –

相關問題