How to add routes to ASP.NET MVC application?
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
Examples:
Suppose you have two controllers: Home and Office. Suppose you have only one action: Index and no id.
If you enter example.com you'd be taken to example.com/Home/Index by default.
Your URLS: example.com/Home and example.com/Office will take you to example.com/Home/Index and to example.com/Office/Index respectively.
If you enter example.com/Sailboat, you'd be given error response.
If you enter example.com/Home/LightsOn/10, you'd be taken to Home controller (usually HomeController), LightsOn action receiving parameter id with value 10.
When do you not need to add routes manually in ASP.NET MVC?
- When you add conventional MVC controllers.
The MVC convention of implementing controllers
By creating classes that derive from the
ControllerBaseclass and giving them names that end with "Controller".The preconfigured routes will invoke the action methods that you implement in the controller classes.
Where can I find default routes in ASP.NET MVC?
- In global.asax file.