Back
Routing and Endpoints in ASP.NET Core

Routing and Endpoints in ASP.NET Core

Routing in ASP.NET Core is a mechanism to match incoming HTTP requests to the appropriate action methods in controllers or endpoints in middleware.

Understanding Routing

Routing is used to map URL patterns to request handlers. In ASP.NET Core, routing is defined in the Program.cs file and can be configured in various ways.

Setting Up Routing

In ASP.NET Core, routes are typically defined in the middleware pipeline. Here’s a basic example of configuring routing in Program.cs:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/", () => "Welcome to ASP.NET Core!");
    endpoints.MapGet("/hello/{name}", (string name) => $"Hello, {name}!");
});

app.Run();

Attribute Routing

Controllers in ASP.NET Core support attribute-based routing:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class HomeController : ControllerBase
{
    [HttpGet("hello/{name}")]
    public IActionResult Hello(string name)
    {
        return Ok($"Hello, {name}!");
    }
}

Using Endpoints

Endpoints in ASP.NET Core provide a way to define request handlers. Middleware components like UseEndpoints help in configuring endpoints.

Conclusion

Routing and endpoints in ASP.NET Core provide flexibility in handling HTTP requests. Whether using conventional routing, attribute routing, or minimal APIs, ASP.NET Core offers powerful tools for defining routes.