WebApi 路由:api/{controller}/{id} 和 api/{controller}/{action} 同时
WebApi Routing: api/{controller}/{id} and api/{controller}/{action} at the same time
我有默认的 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
但得到:
Multiple actions were found that match the request:
CustomAction1 on type MyProject.WebApiService.MyController
CustomAction2 on type MyProject.WebApiService.MyController
确保您配置了属性路由以及默认配置
//....
config.MapHttpAttributeRoutes()
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
);
//....
如果你想在没有属性路由的情况下做同样的事情,那么你需要显式配置路由
//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}"
);
我有默认的 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
但得到:
Multiple actions were found that match the request: CustomAction1 on type MyProject.WebApiService.MyController CustomAction2 on type MyProject.WebApiService.MyController
确保您配置了属性路由以及默认配置
//....
config.MapHttpAttributeRoutes()
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
);
//....
如果你想在没有属性路由的情况下做同样的事情,那么你需要显式配置路由
//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}"
);