Kun*_*vič 10 asp.net-mvc-4 asp.net-web-api
我刚刚创建了asp.net mvc 4 app并添加了默认的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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
然后我试图通过键入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>
Run Code Online (Sandbox Code Playgroud)
我的路线配置:
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 }
);
}
Run Code Online (Sandbox Code Playgroud)
为什么它默认不起作用?我该怎么办才能解决这个问题?
您不需要get输入URL,因为GET是HTTP谓词的类型.
默认情况下,如果您输入URL,浏览器会发送GET请求.
所以试试吧 http://localhost:51416/api/
因为UserApiController如果取消注释defaults: new { controller = "UserApiController"...路由配置中的行,则是默认的api控制器
请注意,指定你的路由时,所以正确的,你不需要"控制器"后缀dafaults设置为:defaults: new { controller = "UserApi", id = RouteParameter.Optional }
)
或者你需要明确指定控制器 http://localhost:51416/api/userapi
您可以在ASP.NET Web API站点上开始了解Wep.API和基于HTTP动词的路由约定.
| 归档时间: |
|
| 查看次数: |
28809 次 |
| 最近记录: |