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

Route Configuration in MVC


The current Route Config for me is this, which I think is the default one

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

When I write

www.mypage.com  
www.mypage.com/home

I get the same page

How Can I make it so that they are two individual pages

www.mypage.com

is the homepage, and

www.mypage.com/home

is another page


Solution

  • www.mypage.com can be handler by a root controller and all the other routes will be handled by the default route.

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

    the explicit defaults allow for the behavior you are currently seeing.

    You will still need to create a controller to handle your root site calls

    public class RootController : Controller {    
        public ActionResult Index() {
            return View();
        }
    }
    

    And don't forget to create the related View for your controller.