2012-06-05 48 views
7

有沒有一種方法可以將查詢字符串參數傳遞給ASP.NET MVC4 Web Api控制器,而無需使用此處概述的OData約定?在不使用OData約定的情況下傳遞查詢字符串參數?

http://www.asp.net/web-api/overview/web-api-routing-and-actions/paging-and-querying

我有一些倉庫使用方法小巧玲瓏不支持IQueryable的,並希望能夠手動分頁他們不使用OData的約定建的,但每當我嘗試做了傳統的ASP.NET方式我收到「路由未找到」錯誤。

例如,這裏有一個路線:

context.Routes.MapHttpRoute(
      name: "APIv1_api_pagination", 
      routeTemplate: "api/v1/{controller}/{id}", 
      defaults: new { area = AreaName, controller = "category", offset = 0, count = 100}); 

而這裏的匹配

public class CategoryController : ApiController 
{ 
    // GET /api/<controller> 
    public HttpResponseMessage Get(int id, int offset = 0, int count = 0) 

簽名每當我通過下面的查詢:

http://localhost/api/v1/category/1?offset=10

我得到出現以下錯誤:

No action was found on the controller 'Category' that matches the request.

任何關於如何在ASP.NET MVC4 Web API中使用querystrings的建議?

+1

我相信這可能是WebAPI中的一個錯誤。你能否嘗試改變你的動作方法參數,使其沒有默認值(併發出一個包含查詢字符串中所有必需值的請求)。 – marcind

+0

當然,我會試試這個。 – Aaronontheweb

回答

2

你的路由器在這種情況下,我也陷入了這個問題的事實是,我有GET多個重載我的WebAPI控制器實例。當我刪除這些內容(並且將所有內容壓縮爲一個具有更多可選參數和方法本身內的控制流的Get方法)時,所有內容都按預期工作。

10

當你開始使用查詢字符串時,你實際上調用其參數的控制器的確切方法。我喜歡你改變你的路由器,如:

context.Routes.MapHttpRoute(
     name: "APIv1_api_pagination", 
     routeTemplate: "api/v1/{controller}/{action}/{id}", 
     defaults: new { area = AreaName, controller = "category", offset = 0, count = 100}); 

,然後改變你的方法爲

public HttpResponseMessage Items(int id, int offset = 0, int count = 0); 

從現在開始,只要你喜歡查詢

http://localhost/api/v1/category/Items?id=1&offset=10&count=0 

它將運行。

在寫這篇文章時,我想到了另一種方法。我不知道,如果它的工作原理,但嘗試改變像

context.Routes.MapHttpRoute(
     name: "APIv1_api_pagination", 
     routeTemplate: "api/v1/{controller}/{id}/{offset}/{count}", 
     defaults: new { area = AreaName, controller = "category", offset = RouteParameter.Optional, count = RouteParameter.Optional}); 
+0

我實際上使用了第二個選項,它可以工作,但它使得URI不直觀,不「可破解」 – Aaronontheweb

相關問題