Routing in ASP.NET Core

Introduction

Routing is a crucial aspect of any web application, determining how incoming requests are matched to specific actions and controllers. In ASP.NET Core, routing is a fundamental component that plays a significant role in handling HTTP requests efficiently. In this article, we will explore routing in ASP.NET Core, understand its concepts, and provide practical examples to help you grasp its functionality effectively.

What is Routing in ASP.NET Core?

Routing in ASP.NET Core is the process of matching incoming HTTP requests to controller actions and determining which action should handle the request. It plays a vital role in URL mapping and directing requests to the appropriate endpoints. The ASP.NET Core routing system uses route templates to define patterns for URLs.

Key components of routing in ASP.NET Core

  1. Route Template: A route template defines the structure of a URL and includes placeholders for route values. For example, /products/{id} is a route template with a placeholder {id}.
  2. Route Values: Route values are extracted from the URL based on the placeholders defined in the route template. In the above example, id is a route value.
  3. Route Constraints: Constraints are used to restrict which URLs match a route template. For instance, you can constrain id to only match numeric values.
  4. Route Parameters: Route parameters are placeholders in controller action methods that correspond to route values. They receive values from the route values extracted from the URL.

Setting Up Routing in ASP.NET Core

Routing in ASP.NET Core is typically configured in the Startup.cs file within the Configure method.

Here's a basic setup for routing.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...

    app.UseRouting();

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

In this setup

  • app.UseRouting() configures the middleware to enable routing.
  • endpoints.MapControllerRoute defines a default route that specifies the controller, action, and an optional ID.

Example. Creating Routes and Controllers

Let's create a simple ASP.NET Core application to demonstrate routing with controllers and actions.

Step 1. Create a New ASP.NET Core Project

You can create a new ASP.NET Core project using Visual Studio or the .NET CLI.

dotnet new mvc -n MyRoutingApp
cd MyRoutingApp

Step 2. Create a Controller

Add a new controller named ProductController with an action method called Details.

using Microsoft.AspNetCore.Mvc;

public class ProductController : Controller
{
    public IActionResult Details(int id)
    {
        // Simulate fetching product details from a database
        var product = new { Id = id, Name = "Sample Product" };
        return View(product);
    }
}

Step 3. Define a Route

In the Startup.cs file, you can define a custom route for the ProductController.

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

In this route, we specify that URLs with the pattern "product/{id:int}" should be routed to the ProductController and the Details action method, where id is constrained to be an integer.

Step 4. Create a View

Create a view of the Details action method. In the Views/Product folder, create a file named Details.cshtml.

@model dynamic
<h1>Product Details</h1>
<p>Product ID: @Model.Id</p>
<p>Product Name: @Model.Name</p>

Step 5. Test the Application

Run the application and navigate to /product/123, your web browser. You should see the product details page with the ID "123" displayed.

Conclusion

Routing in ASP.NET Core is a powerful mechanism for directing HTTP requests to the appropriate controller actions. It enables you to create clean and structured URLs for your web application and provides flexibility in defining custom routes and constraints. Understanding routing is essential for building well-organized and user-friendly web applications in ASP.NET Core.