2013-08-25 40 views
0

我有網頁API的一些問題,和標準文件並沒有幫助我很多..的.NET Web API定製返回值

我有一個ProductsController,有一個默認的方法GetAllProducts(),它接受幾個GET參數(這樣實現起來更容易)來查詢。

現在,在應用程序的另一部分,我使用了一個jQuery自動完成插件,它必須查詢我的web服務並過濾數據。問題是,它期望得到自定義格式的結果,這與Web API返回的格式不同。我開始創建另一種方法GetProductsByQuery(string query),它應該以該格式返回數據。

有什麼辦法可以強制WebAPI以我想要的方式返回數據,而無需製作另一個控制器?

我也有與路由表的問題,因爲所有的GET直奔第一種方法,即使我排到第二個到url: "{controller}/query/{query}"

下面是一些代碼:

公衆ProductsController類:ApiController {

public IEnumerable<Product> GetAllProducts() 
    { 
     NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query); 
     // Querying EF with the parameters in the query string 

     return returnQuery; 
    } 

    [System.Web.Mvc.HttpGet] 
    public dynamic GetProductsByQuery(string query) 
    { 
     return SomeCustomObject; 
    } 

和路由:

 routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 

     routes.MapRoute(
      name: "Query", 
      url: "{controller}/query/{query}"); 
+0

請發表您的代碼。 –

+0

對,錯過了。我發佈了一個精簡版的代碼,用我試過的版本 –

+1

你並不是被迫從ProductsController中返回產品,你可以返回任何你想要的東西。只需返回與您的調用者期望的合約相匹配的自定義對象(假設它期望json輸出)。 –

回答