Barış Kısır

Implementing Attribute Routing in .NET Web API

25 Oct 2016

Optimizing RESTful URIs with Attribute Routing

By default, the .NET Web API framework utilizes convention-based routing, which can result in verbose query strings for complex inputs. This often leads to less intuitive URIs:

http://www.example.com/api/GetProducts?productName={productName}&productCategory={productCategory}

As API surface area expands, maintaining these convention-based routes becomes increasingly difficult. Attribute routing offers a more granular and expressive alternative by allowing routing templates to be defined directly on the controller actions.

Implementation Strategy

Applying the [Route] attribute to an action method allows for the creation of clean, hierarchical URI paths that map directly to your business logic.

[Route("api/Products/GetProducts/{productName}/{productCategory}")]
public List<Product> GetProducts(string productName, string productCategory) 
{
    // Implementation logic here...
}

Advanced Patterns and API Versioning

Attribute routing is particularly advantageous when orchestrating API versioning strategies. This ensures that your infrastructure can support multiple endpoints with minimal configuration.

// Segment-based versioning examples
[Route("api/v1/Products/Lookup/{productName}/{category}")]
public List<Product> GetProductsV1(string productName, string category) { ... }

[Route("api/v2/Products/Search/{name}/{category}")]
public List<Product> GetProductsV2(string name, string category) { ... }

Strategic Benefits

  1. URI Control: Decouples the exposed URI from internal method names.
  2. Navigation Logic: Facilitates hierarchical resource modeling (e.g., api/users/{userId}/settings).
  3. Constraint Enforcement: Supports inline data type validation within the route template (e.g., {id:int}).
  4. Readability: Enhances code discoverability by keeping routing metadata adjacent to the implementation.