In this article, you will know about ASP.NET MVC Routing.
- What is Routing?
- Why Routing is required?
- WebForm vs MVC
- Advantage of Routing
- How to configure Routing?
- How Routing Work?
What is Routing?
In a general sense, Routing means showing a way. ASP.NET MVC Routing does the same thing; it shows the way to a request. Basically, routing is used for handling HTTP requests and searching matching action methods, and then executing the same.
- It constructs outgoing URLs that correspond to controller actions.
- Routing the map request with Controller’s Action Method.
We can call Routing a pattern matching technique which manages the incoming request. It matches the request with Route Table.
Why Routing is required
In MVC, Model View Controller are the main independent components. These three components work individually and all-together at the same time.
Any incoming request is handled by Controller. MVC is not mapped directly with physical UI output file. That is mapped by Controller at run time and route table.
For more information about Route Table and Route Collection, go through the following links.
- http://stackoverflow.com/questions/16691566/whats-the-difference-between-routecollection-and-route-table
- https://msdn.microsoft.com/en-us/library/system.web.routing.routetable(v=vs.110).aspx
WebForm vs MVC
In WebForm technology, URL is directly attached to physical file.
Example: www.myshop.com/plastic/index.aspx
In MVC, URL is not attached with any physical file directly but it's attached with the Action Method of Controller.
Example: www.myshop.com/plastic/index
As you can see in the above URL,
www.myshop.com : Domain Name
plastic : Controller Name
index : Action Method Name
www.myshop.com/bottle/plastic/100
As you can see in the above URL,
www.myshop.com : Domain Name
bottle : Controller Name
plastic : Action Method Name
100 : 100 is a id or Paramter passed to action method
Advantages of Routing
- Routing is very friendly & helpful for SEO (Search Engine Optimization).
- All URLs are not directly mapped with physical file.
- More powerful securities than in WebForm.
How to configure Routing
Configuring / setting routing is very simple. As you see in your solution explorer, there is App_Start folder. In this folder, locate the RouteConfig.cs file.
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller =”<Your Default Controller Name>“, action = "<Your Default Action Name>", id = UrlParameter.Optional }
- );
- }
NOTE - App_Start folder has been introduced in MVC4. This folder has all the settings related files, as you can see in image.
- cs
- cs
- cs
- cs
- Auth.cs
How Routing works