2013-08-01 30 views
0

是否可以向所有控制器添加強制參數? 我開發RESTful api,所以我想爲每個路由都要求特殊的「apikey」參數。AttributeRouting強制性參數

 [HttpPut] 
    [PUT("create")] 
    public PostDto Create(string title, string description, string tag, long photo, float lat, float lon, int error) 
    { 
     if (description.Length > DescriptionMaxLength) 
      throw new ApiException(ErrorList.TooLongDescription, string.Format("Description is more than {0}", DescriptionMaxLength)); 

     throw new NotImplementedException(); 
    } 

    [HttpPost] 
    [POST("edit/{id:int}")] 
    public bool Edit(int id, string title, string description, int? photo) 
    { 
     if (description.Length > DescriptionMaxLength) 
      throw new ApiException(ErrorList.TooLongDescription, string.Format("Description is more than {0}", DescriptionMaxLength)); 

     throw new NotImplementedException(); 
    } 

    [HttpDelete] 
    [DELETE("delete/{id:int}")] 
    public bool Delete(int id) 
    { 
     if (id < 0) 
      throw new ApiException(ErrorList.InvalidValue, "id is smaller than 0"); 

     throw new NotImplementedException(); 
    } 

但我不想爲每種方法手動執行此操作。

+0

對於像'apikey'這樣的必要參數,我將在驗證方法中使用BaseController或ActionFilter進行驗證。如果您稍後需要訪問apikey,則始終可以假定它存在。如果需要,您也可以將過濾器將api鍵推入Context.Items集合中或類似的東西。 –

回答

1

首先,您需要確定您要在操作正文中檢索API密鑰的確切方式。 由於您不想將它作爲方法的參數傳遞,因此它可以是控制器的屬性(不是最好的方法,您必須創建一個自定義基礎控制器類,但它可能適用於簡單場景)或另一個臨時的每個請求存儲。

然後,您需要創建一個Web API操作過濾器。它類似於常規的ASP.NET MVC動作過濾器,網上有很多教程,但大多數都是關於授權的。

此過濾器會嘗試將API密鑰從請求中注入控制器或您選擇的臨時存儲器 - 在過濾器的OnActionExecutingmethod中,您可以訪問請求信息和控制器上下文。

完成後,只需在Web API配置中註冊您的過濾器,這裏是一個example關於如何做到這一點。