Lessons in this course (10)

2. Routing — conventional and attribute routes

Basic★ Must knowLesson 2 of 10
csharp
// App_Start/RouteConfig.cs
public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();                         // enable [Route] attributes (MVC 5)

        routes.MapRoute(
            name: "ProductBySlug",
            url: "products/{category}/{slug}",
            defaults: new { controller = "Products", action = "BySlug" });

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    }
}

// Attribute routing
[RoutePrefix("orders")]
public class OrdersController : Controller
{
    [Route("")] public ActionResult Index() => View();
    [Route("{id:int}")] public ActionResult Details(int id) => View(_orders.Get(id));
    [Route("customer/{customerId:int}/{year:int:min(2000)?}")] public ActionResult ByCustomer(int customerId, int? year) => View();
}

Routes are checked in order — put specific routes before the generic default. Url.Action("Details", "Orders", new { id = 5 }) and Html.ActionLink generate URLs from routes, so URLs change in one place.