0

ASP.NET Web API Attribute Based Routing

ASP.NET Web API Attribute Based Routing

Route attributes bring the URL definition closer to the code that runs for that particular URL, making it easier to understand which URL must be called for a particular block of code and simplifying many common routing scenarios.

For example, let’s say you want to define a Web API that has the standard set of HTTP actions (GET, POST, PUT, DELETE, and so on) but you also want to have an additional custom action, such as Approve. Instead of adding another route to the global route table for the Approve action, you can instead just attribute the action directly:

public class OrdersController : ApiController

{

public IEnumerable<Order> GetOrders() {…}

public Order GetOrder(int id) {…}

public Order Post(Order order) {…}

[HttpPost("orders/{id}/approve")]

public Order Approve(int id) {…}

}

An extended route template syntax makes it simple to specify default values and constraints for route values. For example, you can now easily create two actions that are called based on parameter type. In the following People controller, the id parameter of the GetByID action takes only int values. The GetByName action method contains a default name of “Nick”.

public class PeopleController : ApiController

{

[HttpGet("{name=Nick}")]

public string GetByName(string name) {…}

 

[HttpGet("{id:int}")]

public string GetById(int id) {…}

}

You can also define common route prefixes for your web APIs. For example, you can use route prefixes to set up a resource hierarchy:

[RoutePrefix("movies")]

[RoutePrefix("actors/{actorId}/movies")]

[RoutePrefix("directors/{directorId}/movies")]

public class MoviesController : ApiController

{

public IEnumerable<Movie> GetMovies() {…}

public IEnumerable<Movie> GetMoviesByActor(int actorId) {…}

public IEnumerable<Movie> GetMoviesByDirector(int directorId) {…}

}

Or, you can use route prefixes to handle multiple versions of your web API:

[RoutePrefix("api/v1/customers")]

public class CustomersV1Controller : ApiController {…}

 

[RoutePrefix("api/v2/customers")]

public class CustomersV2Controller : ApiController {…}

Similar to the new CORS support in ASP.NET Web API, the new support for attribute-based routing is largely a contribution from the community.