Search code examples
c#asp.net-mvcurl-routingasp.net-mvc-routing

In MVC, how do I setup 2 routes (one with a hardcoded segment, and the other with an empty segment) to point to the same destination?


I'm trying to setup routes in my MVC application, where one route could have the segment "Portal" and another route has no "Portal" segment at all. Essentially, I need these URLs to send the user to the same page, but I also want /Home/Index to be the default:

/Portal/Home/Index
/Home/Index

I have the following code:

routes.MapRoute(
    "PortalDefault", // Route name
    "Portal/{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional, portal = String.Empty } // Parameter defaults
);

This allows the user to go to /Portal/Home/Index and /Home/Index but the problem is that the website now defaults to /Portal/Home/Index.

I need the website to default to /Home/Index but still allow /Portal/Home/Index


Solution

  • One solution is to add a route for the home page to override PortalDefault.

    routes.MapRoute(
        "Home", // Route name
        "", // URL with parameters
        new { controller = "Home", action = "Index", portal = String.Empty } // Parameter defaults
    );
    
    routes.MapRoute(
        "PortalDefault", // Route name
        "Portal/{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
    
    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional, portal = String.Empty } // Parameter defaults
    );
    

    NOTE: It seems odd that your PortalDefault route doesn't define a route value for portal, but your Default route does.