Routing in Web API

🔄 Routing in Web API

How Routing Works

When a request is made to a Web API endpoint like:

GET /api/products/5

The routing system analyzes the URL and HTTP method, then selects the corresponding controller and action method that matches the pattern.

Types of Routing in ASP.NET Web API



1. Attribute Routing (Recommended in Web API 2 and ASP.NET Core)

Routes are defined directly on controller and action methods using attributes like [Route], [HttpGet], [HttpPost], etc. It provides more control and clarity.


[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetProduct(int id)
    {
        return Ok("Product " + id);
    }
}
      

This route handles:

GET /api/products/5

2. Convention-Based Routing (Used in earlier versions like Web API 1)

Routes are defined in a central location, typically in WebApiConfig.cs. It follows a predefined pattern.


public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
      

This allows a request like:

GET /api/products/10

to call the Get(int id) method in ProductsController.

HTTP Method Mapping

Routing not only matches the URL pattern but also considers the HTTP method:

  • GET maps to Get()
  • POST maps to Post()
  • PUT maps to Put()
  • DELETE maps to Delete()

Method names can be customized when using attributes like [HttpGet], [HttpPost], etc.

Benefits of Routing in Web API

Summary

Routing in Web API is the mechanism that connects incoming HTTP requests to the right controller actions. It can be done through:

Proper routing is essential for creating effective, clean, and intuitive APIs.

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features