Routing is configured in the Configure method of the Startup class. To set the "homepage" simply add the following. This will cause users to be routed to the controller and action defined in the MapRoute method when/if they navigate to your site’s base URL, i.e., yoursite.com will route users to yoursite.com/foo/index:
Use the RegisterRoutes method located in either App_Start/RouteConfig.cs (MVC 3 and 4) or Global.asax.cs (MVC 1 and 2) as shown below. This will cause users to be routed to the controller and action defined in the MapRoute method if they navigate to your site’s base URL, i.e., yoursite.com will route the user to yoursite.com/foo/index:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Here I have created a custom "Default" route that will route users to the "YourAction" method within the "FooController" controller.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "FooController", action = "Index", id = UrlParameter.Optional }
);
}
Before MVC 5 you could map URLs to specific actions and controllers by calling routes.MapRoute(...) in the RouteConfig.cs file. This is where the url for the homepage is stored (Home/Index). However if you modify the default route as shown below,
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
keep in mind that this will affect the URLs of other actions and controllers. For example, if you had a controller class named ExampleController and an action method inside of it called DoSomething, then the expected default url ExampleController/DoSomething will no longer work because the default route was changed.
A workaround for this is to not mess with the default route and create new routes in the RouteConfig.cs file for other actions and controllers like so,
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Example",
url: "hey/now",
defaults: new { controller = "Example", action = "DoSomething", id = UrlParameter.Optional }
);
Now the DoSomething action of the ExampleController class will be mapped to the url hey/now. But this can get tedious to do for every time you want to define routes for different actions. So in MVC 5 you can now add attributes to match urls to actions like so,
public class HomeController : Controller
{
// url is now 'index/' instead of 'home/index'
[Route("index")]
public ActionResult Index()
{
return View();
}
// url is now 'create/new' instead of 'home/create'
[Route("create/new")]
public ActionResult Create()
{
return View();
}
}