这是我的代码:
public class SecurityController : ApiController
{
//GET api/Security/Current
public HttpResponseMessage GetCurrent(){
}
//POST api/Security/Login
public HttpResponseMessage PostLogin(LoginModel model){
}
}
public class OrdersController : ApiController
{
[ActionName("Default")] //GET api/Orders
public HttpResponseMessage Get(){
}
[ActionName("Default")] //GET api/Orders/2
public HttpResponseMessage Get(long id){
}
[ActionName("Default")] //POST api/Orders/
public HttpResponseMessage Post(Order order){
}
[ActionName("Default")] //DELETE api/Orders/2
public HttpResponseMessage Delete(long id){
}
[HttpPost] //POST api/Orders/2/PerformAction
public HttpResponseMessage PerformAction(long id, ActionMsg action){
}
}
//路线定义
config.Routes.MapHttpRoute("ActionApi", "api/{controller}/{action}");
config.Routes.MapHttpRoute("WithActionApi", "api/{controller}/{id}/{action}");
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional, action = "Default" }, new { id = @"\d+" });
我的路由无效。
No HTTP resource was found that matches the request URI
我的API控制器的正确路由定义是什么? 谢谢!
答案 0 :(得分:6)
将SecurityController更改为:
public class SecurityController : ApiController
{
//GET api/Security/Current
[HttpGet]
[ActionName("current")]
public HttpResponseMessage GetCurrent(){
}
//POST api/Security/Login
[HttpPost]
[ActionName("login")]
public HttpResponseMessage PostLogin(LoginModel model){
}
}
然后将路由更改为:
config.Routes.MapHttpRoute("ActionApi",
"api/{controller}/{action}",
null,
new { action = @"[a-zA-Z]+" });
config.Routes.MapHttpRoute("WithActionApi",
"api/{controller}/{id}/{action}");
config.Routes.MapHttpRoute("DefaultApi",
"api/{controller}/{id}",
new { id = RouteParameter.Optional, action = "Default" },
new { id = @"\d*" });
注意在最后一条路线中需要正则表达式“\ d *”而不是“\ d +”。
答案 1 :(得分:0)
请删除:[ActionName("Default")]
您的路线定义均未引用它。事实上,对于web api,你根本不需要动作名称。
删除了ActionName,并使用"api/{controller}/{action}"
路由,您应该可以使用http://url/api/orders
来调用该操作,public HttpResponseMessage Get()
将调用{{1}}