Routing in Web API
🔄 Routing in Web API
Table of Contents
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:
GETmaps toGet()POSTmaps toPost()PUTmaps toPut()DELETEmaps toDelete()
Method names can be customized when using attributes like [HttpGet], [HttpPost], etc.
Benefits of Routing in Web API
- Enables clean, RESTful URLs
- Supports versioning and organized APIs
- Allows easy mapping of multiple endpoints
- Promotes maintainable and scalable API structures
Summary
Routing in Web API is the mechanism that connects incoming HTTP requests to the right controller actions. It can be done through:
- Attribute Routing (preferred for flexibility and clarity)
- Convention-Based Routing (used in older Web API versions)
Proper routing is essential for creating effective, clean, and intuitive APIs.

Comments
Post a Comment