Routes in ASP.NET MVC

Routes in ASP.NET MVC
Routes in ASP.NET MVC

Routes define how URLs map to controllers and actions in your application.

Defining a Route

Routes are usually defined in the RouteConfig class within the App_Start folder:

public class RouteConfig

{

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 }

);

}

}

Custom Routes

You can add custom routes before the default route to match specific patterns:

routes.MapRoute(

name: "Product",

url: "Product/{id}",

defaults: new { controller = "Product", action = "Details" },

constraints: new { id = @"\d+" } // Only match numeric IDs

);


Routes in Razor Pages

In Razor Pages, routes are defined using the @page directive at the top of the .cshtml file.

Basic Route

@page "/product/{id}"

@model ProductModel

<h1>Product Details</h1>

<p>Product ID: @Model.Id</p>

Custom Parameters

You can bind route parameters to properties in the page model:

[BindProperty(SupportsGet = true)]

public int Id { get; set; }


Attribute Routing in ASP.NET Core

In ASP.NET Core, you can define routes directly on controller actions using attributes:

Controller-Level Routing

[Route("api/[controller]")]

public class ProductsController : Controller

{

[HttpGet("{id}")]

public IActionResult GetProduct(int id)

{

return Ok(new { ProductId = id });

}

}


Route Debugging

  • Use tools like [Routing Debugger](click here to troubleshoot route issues.
  • For ASP.NET Core, enable endpoint routing debugging by logging routing data.

Route Testing

  • Manual Testing: Test URLs in your browser or via tools like Postman.
  • Automated Testing: Use unit tests to validate that routes map correctly to the intended controllers/actions.