[英]Webapi custom route action
I've created controller class that extends ApiController and includes following methods : 我创建了扩展ApiController并包括以下方法的控制器类:
// GET api/Posts/5
[ResponseType(typeof(Post))]
public IHttpActionResult GetPost(int id)
{
...
}
// GET api/Posts/ByBoardID/2
[HttpGet]
[ActionName("ByBoardID")]
public IQueryable<Post> GetByBoardID(int boardID)
{
...
}
The idea is to match those method to a given routes (ie 'api/Posts/ByBoardID/2' to a GetByBoardID(int boardID) method and 'api/Posts/2' to a GetPosts(int id) method). 想法是将那些方法匹配到给定的路由(即,将“ api / Posts / ByBoardID / 2”匹配到GetByBoardID(int boardID)方法,将“ api / Posts / 2”匹配到GetPosts(int id)方法)。
Here's route config : 这是路由配置:
config.Routes.MapHttpRoute(
name: "ByParamApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
Second route ('api/Posts/ByBoardID/2') cannot be matched - No HTTP resource was found that matches the request URI
. 无法匹配第二个路由('api / Posts / ByBoardID / 2')-
No HTTP resource was found that matches the request URI
。
Whats the best practice to create such 'nested' routes inside controller? 在控制器内创建此类“嵌套”路由的最佳实践是什么? I will use many controllers with the same pattern
(/{controller}/{id} and /{controller}/bySpecialParam/{id})
so I don't want to 'hardcode' such route that won't be reusable. 我将使用许多具有相同模式的
(/{controller}/{id} and /{controller}/bySpecialParam/{id})
所以我不想“硬编码”这样的路由,使其无法重用。
Only way I ever got working such combination is by changing this 我曾经工作过这种组合的唯一方法是更改此
[ActionName("ByBoardID")]
to 至
[Route("api/Posts/ByBoardID/{boardID}")]
Never able to figure out how the ActionName attribute works so always preferred to go with Route attribute 永远无法弄清楚ActionName属性是如何工作的,因此总是首选与Route属性一起使用
This worked:
这工作:
1) Provide actionName for both the methods in the controller. 1)为控制器中的两个方法提供actionName。
[ActionName("DefaultAction")]
[ActionName("ByBoardID")]
2) In the webapiconfig class, add the following routes 2)在webapiconfig类中,添加以下路由
config.Routes.MapHttpRoute(
"defaultActionRoute",
"{controller}/{action}/{id}",
null,
new
{
action = "ByBoardId"
});
config.Routes.MapHttpRoute(
"defaultRoute",
"{controller}/{id}",
new
{
action = "DefaultAction"
});
Make sure you have the GlobalConfiguration.Configuration.EnsureInitialized();
确保您具有
GlobalConfiguration.Configuration.EnsureInitialized();
at the end of Application_Start()
method. 在
Application_Start()
方法的末尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.