Trending @Microsoft: Routing, by Convention, is how ASP.NET WebAPI matches a URI String to an action. WebAPI 2 supports a new type of routing, which leverages attributes. As the name implies, attribute routing uses attributes to define routes rather than Parametrized Strings, as in WebAPI. Attribute routing provides more control over the URIs and scale of a web API.

This implies…

  • Support for Hierarchical URI schemes
  • Eliminating magic route templates
  • Intuitive route constraints
  • HTTP Method attributes
  • Route prefixes

…And WebAPI 2 now provides the attributes to easily support application modeling. WebAPI and WebAPI 2 are complementing technologies and can be mixed and matched within the same API; let’s look at the similarities, strengths, and weakness of the WebAPI versions…

WebAPI by convention…

  • Routing tables
  • Routing templates
  • Routing actions
  • HTTP Methods
  • OData query
  • MapHttpRoute

WebAPI 2 by attribute…

  • Routing tables
  • Routing attributes
  • Routing actions
  • HTTP attributes
  • OData query
  • MapHttpAttributeRoute

Migrating from WebAPI to WebAPI 2…

One strength of WebAPI by convention, routing rules are applied consistently across all controllers; but convention routing does not easily support versioning, hierarchical URI routes, URI segments, or parameter types; however, WebAPI 2 implements these scenarios easily.

Enabling WebAPI 2 is a matter of configuring MapHttpAttributeRoutes rather the WebAPI MapHttpRoutes. And when WebAPI 2 is enabled, available attributes include HTTP method overrides, class route prefixes, route prefix parameters, optional and default values, route constraints, attribute route names, and route orders.

Complex WebAPI implementations are quickly overwhelmed with routes built from magic parametrized-strings; WebAPI 2 eliminates magic rout templates and replaces them with intuitive and organized attribute decorations. If you’ve been working with WebAPI you’re already familiar with route tables, actions, defaults, and HTTP methods; now WebAPI 2 provides route attributes and moves WebAPI one step further toward a first class REST solution.

Conclusions…

WebAPI 2 is tightly coupled with WebAPI and provides a viable alternative to convention routing, which makes WebAPI easier to use and APIs easer to build and maintain. If you’ve been working with WebAPI, taking advantage of WebAPI 2 will not only seem like a natural step, but help make routing easier and more intuitive.

Additional references…

WebAPI Routing

WebAPI 2 Routing