2013-10-16 115 views
1

我目前遇到了我正在處理的Web Api問題。從同一個控制器路由多個GET方法 - Web Api

我有兩個Get方法的控制器。一個返回對象列表。該方法返回相同對象的名單,但基於被傳入一些參數過濾其他像這樣:

public IList<MyObject> Get(int id) 
{ 
    //Code here looks up data, for that Id 
} 

public IList<MyObject> Get(int id, string filterData1, string filterData2) 
{ 
    //code here looks up the same data, but filters it based on 'filterData1' and 'filterData2' 
} 

我不能讓路線這項工作。尤其是因爲Api幫助頁面似乎多次顯示相同的URL。

我的路線是這樣的:

  config.Routes.MapHttpRoute(
      name: "FilterRoute", 
      routeTemplate: "api/Mycontroller/{Id}/{filterData1}/{filterData2}", 
      defaults: new { controller = "Mycontroller" } 
     ); 

     config.Routes.MapHttpRoute(
      name: "normalRoute", 
      routeTemplate: "api/Mycontroller/{Id}", 
      defaults: new { controller = "Mycontroller" } 
     ); 

任何人都知道嗎?

此外,是否有可能改變我的過濾方法類似

public IList<MyObject> Get(int Id, FilterDataObject filterData) 
{ 
    //code here 
} 

或者你能不能在獲取通過複雜的對象?

+0

你想什麼網址? – lolol

+0

server/api/MyController/1 /「someString」/「someOtherString」和server/api/Mycontroller/1 – MartinM

+0

您嘗試的URL對於您正在創建的路由有誤(查看我的回覆)。 – lolol

回答

1

比方說你有以下途徑:

routes.MapHttpRoute(
    name: "Default", 
    routeTemplate: "api/{controller}/{id}/{p1}/{p2}", 
    defaults: new { id = RouteParameter.Optional, p1 = RouteParameter.Optional, p2 = RouteParameter.Optional }); 

GET api/controller?p1=100地圖public HttpResponseMessage Get(int p1) {}

GET api/controller/1?p1=100地圖public HttpResponseMessage Get(int id, int p1) {}

GET api/controller/1地圖public HttpResponseMessage Get(int id) {}

等等...

GET和複雜模型綁定:根據定義,複雜模型應該位於請求主體(獨立於動詞)(一個url包含可打破複雜模型的長度限制)。您可以強制的WebAPI做尋找在URL中複雜的模型:

routes.MapHttpRoute(
    name: "Default", 
    routeTemplate: "api/{controller}/{customer}"); 

public class Customer 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

public HttpResponseMessage Get([FromUri] Customer customer) {}; 

GET api/customers?id=1&name=Some+name 

剛一說明:用複雜類型GET,大部分的時間(如我的例子)是沒有意義的。爲什麼你應該通過ID和姓名獲得客戶?根據定義,複雜類型需要POST(CREATE)或PUT(UPDATE)。

要使用的子文件夾結構打電話,試試:

routes.MapHttpRoute(
    "MyRoute", 
    "api/{controller}/{id}/{p1}/{p2}", 
    new { id = UrlParameter.Optional, p1 = UrlParameter.Optional, p2 = UrlParameter.Optional, Action = "Get"}); 

GET /api/controller/2134324/123213/31232312 

public HttpResponseMessage Get(int id, int p1, int p2) {}; 
+0

謝謝。我完全同意,這應該是一個職位。事實上,這是一個郵政,但權力是不同意的,所以我在這裏。至於路由,我明白你在說什麼。但是我遇到的問題是我正在使用nuGet包,它向Api添加文檔(幫助頁面)。它定義的路線以你所描述的格式給了我Url,比如'api/controller/1?p1 = p1',但我想明確顯示它們作爲參數,所以api/controller/1/parameter1 – MartinM

+0

@villamartin看看我最近的更新。 – lolol

+0

謝謝,具有可選參數的路線有效。 upvoted。我仍然認爲這是解決這個問題的錯誤方法,並且將過濾器數據的對象張貼起來是更好的解決方案。但現在這會做! – MartinM

1

試試看attribute routing nuget包。這使您可以爲控制器中的每個方法定義自定義URL。

關於你的第二個問題,你不能通過獲取請求發送複雜的對象,因爲沒有請求主體來保存值,你將需要使用POST方法來做到這一點。

相關問題