Search code examples
asp.net-mvcasp.net-mvc-4url-routingasp.net-mvc-routingrouteconfig

MVC4 Routing Subfolder Directory for Checkout


What do I need to do to map these URLs to my routes?

example.com/checkout?o=1234
example.com/checkout/shipping?o=1234
example.com/checkout/payment?o=1234
example.com/checkout/review?o=1234
example.com/checkout/receipt?o=1234

In the RouteConfig, I have these defined:

 routes.MapRoute(
         name: "Checkout",
         url: "checkout",
         defaults: new { controller = "Checkout", action = "Index", o = UrlParameter.Optional }
     );

 routes.MapRoute(
          name: "checkout Prefix",
          url: "Checkout/{controller}/{action}/{o}",
          defaults: new { controller = "Shipping|Payment|Review|Receipt", action = "Index", o = UrlParameter.Optional }
          );

The controller folders are:

 Controllers
      CheckoutController.cs
            Checkout
                 ShippingController.cs
                 PaymentController.cs
                 ReviewController.cs
                 ReceiptController.cs

When I switch the order and but the Checkout Prefix first, it messes up the "checkout?o=" route. When I put the Checkout route first, the second never gets hit.


Solution

  • Your assumption that o is part of the route is incorrect. Query strings are not evaluated as part of the match.

    Also, you should be specifying the regular expression in a constraint, not as a default value.

    routes.MapRoute(
        name: "Checkout",
        url: "checkout",
        defaults: new { controller = "Checkout", action = "Index" }
    );
    
    routes.MapRoute(
        name: "checkout Prefix",
        url: "checkout/{controller}",
        defaults: new { action = "Index" },
        constraints: new { controller = "Shipping|Payment|Review|Receipt" }
    );