WebApi路由:api / {controller} / {id}和api / {controller} / {action}同时

时间:2016-04-15 12:13:49

标签: c# asp.net-web-api asp.net-mvc-routing url-routing

我有默认的webapi路由配置:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional },
);

我想支持以下方案:

//api/mycontroller
public IQueryable<MyDTO> Get();

//api/mycontroller/{id} where id can be anything except "customaction1" and "customaction2"
public HttpResponseMessage Get(string id);

//api/mycontroller/customaction
[HttpPost]
public void CustomAction1([FromBody] string data);
[HttpPost]
public void CustomAction2([FromBody] string data);

我尝试将[Route("api/mycontroller/customaction1")]应用于CustomAction1方法,类似于CustomAction2,但获得了:

  

找到与请求匹配的多个操作:   MyProject.WebApiService.MyController类型的CustomAction1   MyProject.WebApiService.MyController类型上的CustomAction2

1 个答案:

答案 0 :(得分:0)

确保您已将属性路由配置为默认配置

//....
config.MapHttpAttributeRoutes()

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional },
);
//....

如果你想对out属性路由做同样的事情,那么你需要明确配置路由

//This one constrains id to be an int
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { action="Get", id = RouteParameter.Optional },
    constraints : new { id = @"\d" }
);
//This one should catch the routes with actions included
config.Routes.MapHttpRoute(
    name: "ActionRoutes",
    routeTemplate: "api/{controller}/{action}"
);