ASP.NET MVC Routing: Mapping URLs to Controller Actions for SEO and User Experience

Understand how routing works in ASP.NET MVC to map incoming URLs to controller actions. This tutorial explains how to configure routes, create user-friendly URLs, and improve your website's search engine optimization (SEO) through effective URL design.



ASP.NET MVC Routing: Mapping URLs to Controller Actions

Introduction to Routing in ASP.NET MVC

Routing in ASP.NET MVC is the process of mapping incoming browser requests (URLs) to specific controller actions. This allows you to create user-friendly URLs that reflect the structure of your application and improves the SEO of your website. Each MVC application has a default route defined in the RouteConfig.cs file.

Default Routing in ASP.NET MVC

The RouteConfig.cs file (typically located in the App_Start folder of your project) contains the route configuration for your application. Initially, it defines a default route:

Default Route Configuration (RouteConfig.cs)

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

This means that a request to the root URL (e.g., localhost:port) will map to the Index action of the Home controller.

Default Route Output

(A screenshot of the default output of the application when accessed via the root URL would be included here. The output will show the content returned by the default controller action.)

Creating and Configuring Custom Routes

Let's create a new controller (StudentsController) and add a route for it in RouteConfig.cs.

StudentsController.cs

using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
public class StudentsController : Controller
{
    public ContentResult Index()
    {
        return Content("This is the default student page");
    }
}
}
Modified Route Configuration (RouteConfig.cs)

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        name: "Students",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Students", action = "Index", id = UrlParameter.Optional }
    );
}

Now, a request to localhost:port/Students/Index will execute the Index action in the StudentsController.

Custom Route Output

(A screenshot showing the output from the Students controller would be included here. The output should match the content returned by the Index() action in the StudentsController.cs file.)