我刚创建了一个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 }
);
}
为什么默认情况下它不起作用?我该怎么做才能修复它?
http://localhost:51416/api
时出现了"无法找到资源"的错误,但是http://localhost:51416/api/userapi
可以访问:)。如何修复http://localhost:51416/api
路由? - angularrocks.comhttp://localhost:51416/api
正常工作,请从路由中 取消注释 此行:defaults: new { controller = "UserApiController", id = RouteParameter.Optional }
,因为在此处您可以指定路由的默认控制器。 - nemesvdefaults: new { controller = "UserApiController", id = RouteParameter.Optional }
,但在调用localhost:51416/api/
时仍然出现“找不到资源”的错误。 - angularrocks.comnew { controller = "UserApi", id = RouteParameter.Optional }
。 - nemesv