[英]WebApi Routing: api/{controller}/{id} and api/{controller}/{action} at the same time
I have default webapi routing configuration: 我有默认的webapi路由配置:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
);
I want to support following scenarios: 我想支持以下场景:
//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);
I have tried to apply [Route("api/mycontroller/customaction1")]
to the CustomAction1
method, and similar to CustomAction2
but getting: 我试图将[Route("api/mycontroller/customaction1")]
应用于CustomAction1
方法,类似于CustomAction2
但得到:
Multiple actions were found that match the request: CustomAction1 on type MyProject.WebApiService.MyController CustomAction2 on type MyProject.WebApiService.MyController 找到了与请求匹配的多个操作:类型为MyProject.WebApiService.MyController的类型MyProject.WebApiService.MyController CustomAction2上的CustomAction1
Make sure that you configured attribute routing along with your default configuration 确保已将属性路由配置为默认配置
//....
config.MapHttpAttributeRoutes()
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
);
//....
If you want to do the same with out attribute routing then you will need to configure routes explicitly 如果要对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}"
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.