2013-07-08 21 views
2

我有一個MVC4應用程序,我創建了一個基於測試的WebAPI控制器,看起來像:空的MVC4應用程序,如何創建一個簡單的測試Web API控制器返回JSON?

public class User1 
    { 
     public int Id { get; set; } 
     public string name { get; set; } 
     public User1(int id, string name) 
     { 
      this.Id = id; 
      this.name = name; 
     } 
    } 

    public class Test1Controller : ApiController 
    { 
     public User1 Get(int id) 
     { 
      return new User1(id, "hello"); 
     } 
    } 

我注意到,我有一個webapiconfig類:

public static void Register(HttpConfiguration config) 
     { 
      config.Routes.MapHttpRoute(
       name: "DefaultApi", 
       routeTemplate: "api/{controller}/{id}", 
       defaults: new { id = RouteParameter.Optional } 
      ); 
     } 

我假定這將默認輸出json結果是否正確?

當我去:

http://localhost:61146/api/test1/get/1 

http://localhost:61146/test1/get/1 

我得到這個錯誤:

The resource cannot be found. 

這究竟是如何映射的,還是我不得不放棄它一個特殊文件夾?我猜測它會自行映射它,因爲我從ApiController繼承

+0

或者web api只響應一個json GET請求?我希望它在瀏覽器中吐出json – loyalflow

+1

看起來你的路由缺少'/ {action} /'參數,不是嗎? *編輯*猜猜不 - 默認項目創建該路線。 API調用必須以不同的方式工作(並且我沒有太多經驗) –

+0

@BradChristie應該在哪裏,抱歉不要跟着你。(編輯)哦行動,讓我試試看,它看起來像缺少,奇怪! (編輯2)是的,這是問題,謝謝! – loyalflow

回答

5

在Web API中,名稱Post,Get,Put,Delete(默認情況下)映射爲請求方法名稱,而不是操作名稱。你的API途徑是:

api/{controller}/{id} 

和請求:

api/test1/get/1 

沒有合適的匹配會被發現,因爲該框架將嘗試匹配4個令牌現存唯一的路由定義,包含3個令牌(字面api和兩個標記:controllerid)。

如果你嘗試:

api/test1/get 

框架將正確地找到Test1Controller,但是,基於路由配置,將令牌"get"綁定到id參數。當框架根據您的請求(GET請求)嘗試找到合適的方法時,它會找到Get(int id)並找到一個匹配項,但無法將令牌"get"轉換爲整數,這表示該方法不是一個好方法請求的候選人。

但是,如果你嘗試這個請求:

api/test1/1 

將令牌"1"轉換成整數1和方法Get(int id)將是一個匹配。

在Asp.NET Web API中,路由有時會令人困惑。我發現明確映射我的路線可以讓我更好地理解請求。我建議AttributeRouting這將是integrated in the next version of the Web Api

相關問題