I just checked attribute routing in ASP.NET Web API 2. In that I can use RoutePrefix
attribute at class level to set prefix to all action name URL. Mostly I use action name as URL routing for particular action. Is there any way that I write a single line of code which set action name as default value for Route
attribute for all action? I want that because I am using action name as URI template, so it will be duplication on top of each action name.
[RoutePrefix("api")]
//[Route("{action}")] // Possible I could write like this
public class BooksController : ApiController
{
[Route("GetBooks")] //Route value same as action name, http://localhost:xxxx/api/GetBooks
public object GetBooks() { ... }
[Route("CreateBook")] //Route value same as action name, http://localhost:xxxx/api/CreateBook
[HttpPost]
public object CreateBook(Book book) { ... }
}
EDIT 1: I want to use attribute routing because I want web API URL pattern like this http://hostname/api/action_name
. My application uses single API controller, so I don't want controller name as part of action URI.
Solution: [Route("{action}")]
on class level will work, if you remove route attribute from all other action unless you want to override for any action.
Personally I would just not use attribute routing and instead use the standard route mapping. So in your App_Start/RouteConfig.cs
file:
routes.MapRoute(
name: "Api",
url: "api/{action}",
defaults: new { controller = "Books" }
);