Routing and Action Selection in Web API

Routing and action selection are fundamental concepts in ASP.NET Web API that determine how HTTP requests are mapped to controller actions. In this detailed lesson, we’ll explore routing and action selection in Web API, along with code examples to illustrate these concepts.

Routing in ASP.NET Web API

Routing refers to the process of determining which controller action should handle an incoming HTTP request based on the request’s URL and HTTP verb. ASP.NET Web API uses a routing table to match URLs to controller actions.

Code Example: Defining Routes

// Define a custom route in WebApiConfig.cs
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

In this example, we define a custom route named “DefaultApi” with a template that includes placeholders for the controller name and an optional “id” parameter.

Action Selection in ASP.NET Web API

Action selection is the process of determining which action method in a controller should handle a specific HTTP request based on the HTTP verb and route parameters.

Code Example: Action Selection

[Route("api/products")]
public class ProductsController : ApiController
{
    [HttpGet]
    public IHttpActionResult GetAllProducts()
    {
        // Handle GET request for all products
        // ...
    }

    [HttpGet]
    [Route("{id:int}")]
    public IHttpActionResult GetProductById(int id)
    {
        // Handle GET request for a specific product by ID
        // ...
    }

    [HttpPost]
    public IHttpActionResult CreateProduct(Product product)
    {
        // Handle POST request to create a new product
        // ...
    }
}

In this example, the [HttpGet] attribute on GetAllProducts and GetProductById methods indicates that they should handle GET requests. The [HttpPost] attribute on CreateProduct indicates that it should handle POST requests.

Route Parameters and Constraints

Route parameters can be used to capture values from the URL and pass them as arguments to action methods. You can apply constraints to route parameters to specify their data types or validation rules.

Code Example: Route Parameters and Constraints

[Route("api/orders")]
public class OrdersController : ApiController
{
    [HttpGet]
    [Route("{id:int}")]
    public IHttpActionResult GetOrderById(int id)
    {
        // Handle GET request for a specific order by ID
        // ...
    }

    [HttpGet]
    [Route("customer/{customerId:int:min(1)}")]
    public IHttpActionResult GetOrdersByCustomer(int customerId)
    {
        // Handle GET request for orders by customer ID
        // ...
    }
}

In this example, {id:int} and {customerId:int:min(1)} are route parameters with constraints. The id parameter must be an integer, and the customerId parameter must be an integer greater than or equal to 1.

Route Order and Ambiguity

In cases where multiple routes match a request, the route with the highest precedence (defined first) is selected. To resolve ambiguity, you can use route order and constraints.

Code Example: Route Order and Ambiguity Resolution

[RoutePrefix("api/orders")]
public class OrdersController : ApiController
{
    [HttpGet]
    [Route("{id:int}")]
    public IHttpActionResult GetOrderById(int id)
    {
        // Handle GET request for a specific order by ID
        // ...
    }

    [HttpGet]
    [Route("customer/{customerId:int}")]
    public IHttpActionResult GetOrdersByCustomer(int customerId)
    {
        // Handle GET request for orders by customer ID
        // ...
    }
}

In this example, the GetOrderById route has a higher order because it’s defined before GetOrdersByCustomer. If a request matches both routes, the one with the higher order is selected.

Conclusion

Routing and action selection are essential parts of ASP.NET Web API that determine how HTTP requests are processed. By defining routes, applying constraints, and understanding route order, you can create a well-structured and predictable API that efficiently maps HTTP requests to the appropriate controller actions.