簡體   English   中英

具有多個參數的 Web API 路由

[英]Web API routing with multiple parameters

我正在嘗試研究如何為以下 Web API 控制器進行路由:

public class MyController : ApiController
{
    // POST api/MyController/GetAllRows/userName/tableName
    [HttpPost]
    public List<MyRows> GetAllRows(string userName, string tableName)
    {
        ...
    }

    // POST api/MyController/GetRowsOfType/userName/tableName/rowType
    [HttpPost]
    public List<MyRows> GetRowsOfType(string userName, string tableName, string rowType)
    {
        ...
    }
}

目前,我正在為 URL 使用此路由:

routes.MapHttpRoute("AllRows", "api/{controller}/{action}/{userName}/{tableName}",
                    new
                    {
                        userName= UrlParameter.Optional,
                        tableName = UrlParameter.Optional
                    });

routes.MapHttpRoute("RowsByType", "api/{controller}/{action}/{userName}/{tableName}/{rowType}",
                    new
                    {
                        userName= UrlParameter.Optional,
                        tableName = UrlParameter.Optional,
                        rowType= UrlParameter.Optional
                    });

但目前只有第一種方法(帶有 2 個參數)有效。 我是在正確的路線上,還是我的 URL 格式或路由完全錯誤? 路由對我來說似乎是黑魔法......

我已經看到WebApiConfig變得“失控”,其中放置了數百條路由。

相反,我個人更喜歡屬性路由

你讓它與 POST 和 GET 混淆

[HttpPost]
public List<MyRows> GetAllRows(string userName, string tableName)
{
   ...
}

HttpPostGetAllRows

為什么不這樣做:

[Route("GetAllRows/{user}/{table}")]
public List<MyRows> GetAllRows(string userName, string tableName)
{
   ...
}

或更改為 Route("PostAllRows" 和 PostRows 我認為您確實在執行 GET 請求,因此我顯示的代碼應該適合您。您來自客戶端的調用將是 ROUTE 中的任何內容,因此它將使用 GetAllRows 找到您的方法,但是方法本身,該名稱可以是您想要的任何名稱,因此只要調用者與 ROUTE 中的 URL 匹配,您就可以為該方法放入 GetMyStuff(如果您真的想要的話)。

更新:

我實際上更喜歡explicit使用HTTP methods類型,並且我更喜歡將路由參數與方法參數匹配

[HttpPost]
[Route("api/lead/{vendorNumber}/{recordLocator}")]
public IHttpActionResult GetLead(string vendorNumber, string recordLocator)
{ .... }

(路由lead不需要匹配方法名稱GetLead但您希望在路由參數和方法參數上保持相同的名稱,即使您可以更改順序,例如將 recordLocator 放在 vendorNumber 之前,即使路由是相反的 -我不這樣做,因為為什么看起來更令人困惑)。

獎勵:現在你也可以在路由中使用正則表達式,例如

[Route("api/utilities/{vendorId:int}/{utilityType:regex(^(?i)(Gas)|(Electric)$)}/{accountType:regex(^(?i)(Residential)|(Business)$)}")]
public IHttpActionResult GetUtilityList(int vendorId, string utilityType, string accountType)
    {

問題是您的api/MyController/GetRowsOfType/userName/tableName/rowType URL 將始終匹配第一個路由,因此永遠不會到達第二個路由。

簡單修復,首先注冊您的RowsByType路由。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM