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

Custom routing in ASP.NET MVC


I have created two different cases of map routes in routeconfig.cs.

// case 1
routes.MapRoute("Default2","{x}", new {controller = "Home", action = "Index"});
// case 2
routes.MapRoute("Default3","{controller}", new {controller = "Home", action = "Index"});

The question is if I use case 1 and input is example.com then the url pattern is not matched even though default controller and action is provided

for the case 2 and input is example.com it fires default controller and action. Why does that happen?

I believe that must happen with case 1 also but what could be the reason? Any help is greatly appreciated.


Solution

  • In this case:

    // case 1
    routes.MapRoute("Default2","{x}", new {controller = "Home", action = "Index"});
    

    You are not defining a default value for the placeholder {x}, therefore this route requires exactly 1 segment (that can contain any value) in order to match the URL. So it will match /foo or /bar, but will not match / or /foo/bar.

    In this case:

    // case 2
    routes.MapRoute("Default3","{controller}", new {controller = "Home", action = "Index"});
    

    You are supplying a default value for {controller} which takes effect when it is not supplied in the URL. Therefore, it will match the URL / and will route to the HomeController.Index method in this case.