我有一個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繼承
或者web api只響應一個json GET請求?我希望它在瀏覽器中吐出json – loyalflow
看起來你的路由缺少'/ {action} /'參數,不是嗎? *編輯*猜猜不 - 默認項目創建該路線。 API調用必須以不同的方式工作(並且我沒有太多經驗) –
@BradChristie應該在哪裏,抱歉不要跟着你。(編輯)哦行動,讓我試試看,它看起來像缺少,奇怪! (編輯2)是的,這是問題,謝謝! – loyalflow