我刚刚创建了 asp.net mvc 4 应用程序并添加了默认 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 }
);
}
为什么默认情况下它不起作用?我能做些什么来解决这个问题?