Routing in ASP.NET Core Web API maps incoming HTTP requests to controller actions. It determines which action handles a request based on the URL, HTTP method, and route template. ASP.NET Core supports attribute routing and conventional routing.
Key Features:
- Maps requests to controller actions
- Supports attribute-based and conventional routing
- Works with RESTful APIs and multiple HTTP methods
- Enables route constraints and parameters
- Integrates with versioning and middleware
Example – Attribute Routing:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetProduct(int id)
{
return Ok($"Product ID: {id}");
}
}
Example – Conventional Routing in Program.cs:
app.MapControllerRoute(
name: "default",
pattern: "api/{controller=Products}/{action=Get}/{id?}");
Routing in ASP.NET Core Web API ensures requests are handled correctly, providing clear URLs and supporting RESTful design principles.
Citations: