Search code examples
c#asp.net-mvcasp.net-mvc-routing

MVC routes are in conflict


I need to have 2 routes in my ASP.NET MVC application, and I am having difficulty trying to define the routes in a way that they don't steal from each other.

  1. I need to handle urls like

www.website.com/Home/About

www.website.com/Home/Contact

  1. I also need to urls like this

www.website.com/23a244x3/Products/2

www.website.com/434e5s344/Services/1

www.website.com/f2432g423/Profile

So I need 2 routes.

The urls in #1 are successfully handled by the default route, which is

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

To handle the urls in #2, I have defined the following route

routes.MapRoute(
    name: "PagesRoute",
    url: "{uniqueID}/{action}/{pagecount}",
    defaults: new { controller = "Pages", pagecount = UrlParameter.Optional }
);

Unfortunately now the route #2 (aka PagesRoute) is also handling the urls from #1, such as www.website.com/Home/About. I also have url rewrite rules set in IIS that turn all urls into lowercase, for SEO purposes, so /Home redirects to /home etc.

How can I differentiate these two routes? The route in #2 seems to be greedy..


Solution

  • You would have to not provide controller, and provide routes for each controller:

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

    To the parser {uniqueID} and {controller} are essentially the same. Any string in the Url, will match both routes, so you need something to differentiate the 2.

    You can also take a look into Route Constraints:

    routes.MapRoute(
        "PagesRoute",
        "{uniqueID}/{action}/{pagecount}",
        new { controller = "Pages", pagecount = UrlParameter.Optional },
        new { uniqueID = @"\d+" }
    );