Detailed technical blog post on conventional routing in .NET Core 6 MVC application:


Routing is a fundamental aspect of ASP.NET Core MVC, enabling developers to define URL patterns and direct incoming HTTP requests to the appropriate controllers and actions. In this comprehensive guide, we’ll explore conventional routing, a powerful feature that allows for structured and predictable URL mappings within .NET Core 6 MVC applications.

Understanding Conventional Routing:

What is Conventional Routing?

Conventional routing in ASP.NET Core MVC follows a convention-based approach to define URL patterns and map them to controller actions. It relies on a set of predefined rules to match incoming requests with specific controllers and their actions.

Route Templates:

Route templates define URL patterns that are matched against incoming requests. They consist of placeholders for dynamic segments in the URL.

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});
  • {controller} and {action} placeholders represent the controller and action names, respectively.
  • {id?} denotes an optional parameter (? indicates optional).

Controller and Action Naming Conventions:

Conventional routing relies on naming conventions to match controllers and actions.

  • Controllers should have names ending with “Controller” (e.g., HomeController).
  • Action methods should be public and named as per the intended action (e.g., Index, Details, etc.).

Example of Conventional Routing:

Configuration in Program.cs:

Configure routing in the Program.cs file :

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.
        builder.Services.AddControllersWithViews();

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (!app.Environment.IsDevelopment())
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

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

        app.Run();
    }
}

MapControllerRoute is used to create a single route. The single route is named default route. Most apps with controllers and views use a route template similar to the default route. REST APIs should use attribute routing.

The route template “{controller=Home}/{action=Index}/{id?}”:

Matches a URL path like /Products/Details/5

Extracts the route values { controller = Products, action = Details, id = 5 } by tokenizing the path. The extraction of route values results in a match if the app has a controller named ProductsController and a Details action.

  • The first path segment, {controller=Home}, maps to the controller name.
  • The second segment, {action=Index}, maps to the action name.
  • The third segment, {id?} is used for an optional id. The ? in {id?} makes it optional. id is used to map to a model entity.

Using this default route, the URL path:

  • /Products/List maps to the ProductsController.List action.
  • /Blog/Article/17 maps to BlogController.Article and typically model binds the id parameter to 17

Controller and Actions:

Create controllers and actions following the naming conventions:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

URL Generation:

Use Url.Action or Html.ActionLink to generate URLs based on route templates.

<a asp-controller="Home" asp-action="Index">Home</a>

Multiple conventional routes

We can define multiple conventional routes. There is no restriction to how many MapControllerRoute we call in Program.cs. We use this to add convention based routing for different style of endpoints

app.MapControllerRoute(name: "blog",
                pattern: "blog/{*article}",
                defaults: new { controller = "Blog", action = "Article" });
app.MapControllerRoute(name: "default",
               pattern: "{controller=Home}/{action=Index}/{id?}");

The route for the  blog in the example above is called a dedicated conventional route. It’s called a dedicated conventional route because:

  • It uses conventional routing.
  • It’s dedicated to a specific action.

Because controller and action don’t appear in the route template "blog/{*article}" as parameters:

  • They can only have the default values { controller = "Blog", action = "Article" }.
  • This route always maps to the action BlogController.Article.

/Blog/Blog/Article, and /Blog/{any-string} are the only URL paths that match the blog route.

The preceding example:

  • blog route has a higher priority for matches than the default route because it is added first.
  • Is an example of slug style routing where it’s typical to have an article name as part of the URL.

Deep Dive Analysis:

Flexibility and Predictability:

Conventional routing offers a balance between flexibility and predictability, allowing developers to define URL patterns logically while adhering to naming conventions.

Convention over Configuration:

By following conventions, developers can avoid explicit route configuration in most cases, promoting a standardized structure across the application.

Parameter Binding:

Conventional routing automatically binds URL segments to action method parameters, simplifying data retrieval from requests.

Conclusion:

Conventional routing in .NET Core 6 MVC applications streamlines URL mapping by leveraging naming conventions and route templates. Understanding this routing mechanism is essential for building scalable, maintainable, and predictable web applications in ASP.NET Core MVC.

By harnessing the power of conventional routing, developers can create structured and consistent URL patterns, enhancing the overall architecture and usability of their applications.