当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Webapi custom route action

问题描述:

Situation :

I've created controller class that extends ApiController and includes following methods :

 // 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 (i.e 'api/Posts/ByBoardID/2' to a GetByBoardID(int boardID) method and 'api/Posts/2' to a GetPosts(int id) method).

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

Problem :

Second route ('api/Posts/ByBoardID/2') cannot be matched - No HTTP resource was found that matches the request URI.

Question :

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.

网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: