0

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.

0

1 Answer 1

1

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" }
);
Sign up to request clarification or add additional context in comments.

1 Comment

Your solution is good. Though [Route("{action}")] on class level is working. I don't know why it didn't work earlier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.