本文介绍了Asp.Net的Web API路由不打自定义操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的code:
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+" });
我的路由不工作。
My routing is not working.
No HTTP resource was found that matches the request URI
什么是我的API控制器正确的路由定义是什么?
谢谢!
What is the correct route definition for my API controller?Thanks!
推荐答案
您SecurityController更改为:
Change your SecurityController to:
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){
}
}
然后你的路由更改为:
And then change your routing to:
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 +。
Note the regex "\d*" is required in the last route rather than "\d+".
这篇关于Asp.Net的Web API路由不打自定义操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!