Routing is the process of mapping incoming HTTP requests to the appropriate handler (action method in MVC or Razor Page handler). ASP.NET Core provides a flexible routing system that allows you to define how URLs are constructed and how they are matched to your application's endpoints.
Routing is configured in the Startup.cs
(or Program.cs
in .NET 6+) file within the Configure
method.
This is often the default setup. In Configure
:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
In this example:
name: "default"
: The name of the route.pattern: "{controller=Home}/{action=Index}/{id?}"
: Defines the URL structure.
{controller}
: Placeholder for the controller name (e.g., `Products`, `Users`). Defaults to `Home` if not provided.{action}
: Placeholder for the action method name (e.g., `List`, `Details`). Defaults to `Index` if not provided.{id?}
: An optional parameter named `id`.Attribute routing is generally preferred for its explicitness and flexibility. It's enabled by default when you use MapControllerRoute
or MapRazorPages
in .NET Core 3.0 and later.
using Microsoft.AspNetCore.Mvc;
namespace MyWebApp.Controllers
{
public class ProductController : Controller
{
[HttpGet]
[Route("products")]
public IActionResult List()
{
return View(); // Renders Products/List.cshtml
}
[HttpGet]
[Route("products/{id:int}")] // Matches /products/123, where 123 is an integer
public IActionResult Details(int id)
{
// Logic to fetch product by id
ViewBag.ProductId = id;
return View(); // Renders Products/Details.cshtml
}
[HttpPost]
[Route("products/create")]
public IActionResult Create([FromBody] Product product)
{
// Logic to create product
return Ok();
}
}
}
For Razor Pages, routing is often handled by convention, but you can override it using the [Route]
attribute on the PageModel.
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc; // Required for [Route] attribute
namespace MyWebApp.Pages
{
// Default routing is /About
// [Route("company/about-us")] // Uncomment to change the route
public class AboutModel : PageModel
{
public string Message { get; set; }
public void OnGet()
{
Message = "Your application description page.";
}
}
}
To ensure attribute routing is used, include the following in your Startup.cs
(or Program.cs
):
// In ConfigureServices
services.AddControllersWithViews(); // For MVC
services.AddRazorPages();
// In Configure
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers(); // Enables attribute routing for controllers
endpoints.MapRazorPages(); // Enables attribute routing for Razor Pages
});
Constraints allow you to specify requirements for route parameters. They are added within curly braces after the parameter name, separated by a colon.
Common constraints include:
int
: Matches an integer.alpha
: Matches only alphabetic characters.guid
: Matches a GUID.datetime
: Matches a date and time.minlength(number)
: Matches a minimum length.maxlength(number)
: Matches a maximum length.regex(pattern)
: Matches a regular expression.
[Route("users/{userId:guid:minlength(36)}")]
public IActionResult UserProfile(Guid userId) { ... }
The order in which you configure middleware in the Configure
method is crucial. app.UseRouting()
must come before app.UseEndpoints()
.
For detailed information and more advanced scenarios, refer to the official ASP.NET Core documentation.