Asp.Net Web API Routing not hitting custom action

谁都会走 提交于 2019-12-30 10:37:38

问题


Here is my 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){

    }

}

//Route definitions

        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 

What is the correct route definition for my API controller? Thanks!


回答1:


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*" });

Note the regex "\d*" is required in the last route rather than "\d+".




回答2:


Please remove: [ActionName("Default")]

None of your route definitions refer to it. In fact, you don't really need action names at all for web api in general.

With ActionName removed, and with "api/{controller}/{action}" route, you should be able to hit that action by using http://url/api/orders which will call public HttpResponseMessage Get()



来源:https://stackoverflow.com/questions/17184798/asp-net-web-api-routing-not-hitting-custom-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!