Routing Configuration in ASP.NET Core MVC and Razor Pages

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.

Core Concepts

Configuring Routing

Routing is configured in the Startup.cs (or Program.cs in .NET 6+) file within the Configure method.

Example: Using Convention-based Routing (Legacy)

This is often the default setup. In Configure:


app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});
        

In this example:

Example: Using Attribute Routing (Recommended)

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.

MVC Controller Example

Controller: ProductController.cs


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();
        }
    }
}
                

Razor Pages Example

For Razor Pages, routing is often handled by convention, but you can override it using the [Route] attribute on the PageModel.

Razor Page: Pages/About.cshtml.cs


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.";
        }
    }
}
                

Enabling Attribute Routing

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
});
        

Route Constraints

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:

Example with Constraints


[Route("users/{userId:guid:minlength(36)}")]
public IActionResult UserProfile(Guid userId) { ... }
        
Note: In modern ASP.NET Core (.NET 6+), the `Program.cs` file handles most of this configuration using minimal APIs syntax, which can be more concise.

Order of Configuration

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.

Official ASP.NET Core Routing Documentation