22
DecRouting in Asp.Net MVC with example
Routing in Asp.Net MVC: An Overview
Basically, Routing is a pattern-matching system that monitors the incoming request and figures out what to do with that request. At runtime, the Routing engine uses the Route table to match the incoming request's URL pattern against the URL patterns defined in the Route table. You can register one or more URL patterns to the Route table at the Application_Start event. MVC5 also supports attribute routing, to know more refer to Attribute Routing in ASP.NET MVC.
In this MVC Tutorial, we will explore more about Routing in Asp.Net MVC which will include asp.net mvc routing in-depth, the workings of routing, the difference between routing and URL rewriting, routing vs URL rewriting. Consider our ASP.NET MVC Course for a better understanding of all MVC core concepts.
How to define a route in Asp.Net MVC...
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // Route Pattern
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Default values for above defined parameters
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
//To:DO
}
When the routing engine finds a match in the route table for the incoming request's URL, it forwards the request to the appropriate controller and action. If there is no match in the route table for the incoming request's URL, it returns a 404 HTTP status code.
Note
Always remember route name should be unique across the entire application. The route name can’t be duplicated.
How it works...
In the above example, we have defined the Route Pattern {controller}/{action}/{id} and also provided the default values for controller, action, and id parameters. Default values mean if you will not provide the values for the controller or action or ID defined in the pattern then these values will be served by the routing system.
Suppose your web application is running on www.example.com then the url pattern for your application will be www.example.com/{controller}/{action}/{id}. Hence you need to provide the controller name followed by the action name and ID if it is required. If you will not provide any of the values then the default values of these parameters will be provided by the routing system. Here is a list of URLs that match and don't match this route pattern.
Difference between Routing and URL Rewriting
Many developers compare routing to URL rewriting that is wrong. Since both approaches are very much different. Moreover, both approaches can be used to make SEO-friendly URLs. Below is the main difference between these two approaches.
URL rewriting is focused on mapping one URL (new URL) to another URL (old URL) while routing is focused on mapping a URL to a resource.
URL rewriting rewrites your old URL to a new one while routing never rewrites your old URL to a new one but it maps to the original route.