Routing in ASP.NET Core is a mechanism to match incoming HTTP requests to the appropriate action methods in controllers or endpoints in middleware.
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.
Program.cs
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();
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}!"); } }
Endpoints in ASP.NET Core provide a way to define request handlers. Middleware components like UseEndpoints help in configuring endpoints.
UseEndpoints
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.