我剛剛創建asp.net的MVC 4應用程序,並添加默認的WebAPI控制器如何調用WebApi控制器方法?
public class UserApiController : ApiController
{
// GET api/default1
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/default1/5
public string Get(int id)
{
return "value";
}
// POST api/default1
public void Post(string value)
{
}
// PUT api/default1/5
public void Put(int id, string value)
{
}
// DELETE api/default1/5
public void Delete(int id)
{
}
}
然後我試圖通過在瀏覽器中鍵入http://localhost:51416/api/get
但得到錯誤調用get()方法:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:51416/api/get'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'get'.
</MessageDetail>
</Error>
我的路線配置:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
//defaults: new { controller = "UserApiController", id = RouteParameter.Optional }
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
爲什麼它沒有被默認的工作? 我能做些什麼來解決這個問題?
正在嘗試'http:// localhost:51416/api'正在獲取資源無法找到。但是'http:// localhost:51416/api/userapi' working :)。如何修復'http:// localhost:51416/api'路由? – Kuncevic
爲了使'http:// localhost:51416/api'工作** uncomment **這條線路由:defaults:new {controller =「UserApiController」,id = RouteParameter.Optional}'因爲你指定了default路由器 – nemesv
的控制器與'defaults:new {controller =「UserApiController」,id = RouteParameter.Optional}搭配「,但仍然無法找到資源。當調用'localhost:51416/api /' – Kuncevic