Routing in ASP.NET Core Web API Explained

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:

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *