English 中文(简体)
MVC Framework - Routing Engine
  • 时间:2024-11-03

MVC Framework - Routing Engine


Previous Page Next Page  

ASP.NET MVC Routing enables the use of URLs that are descriptive of the user actions and are more easily understood by the users. At the same time, Routing can be used to hide data which is not intended to be shown to the final user.

For example, in an apppcation that does not use routing, the user would be shown the URL as http://myapppcation/Users.aspx?id=1 which would correspond to the file Users.aspx inside myapppcation path and sending ID as 1, Generally, we would not pke to show such file names to our final user.

To handle MVC URLs, ASP.NET platform uses the routing system, which lets you create any pattern of URLs you desire, and express them in a clear and concise manner. Each route in MVC contains a specific URL pattern. This URL pattern is compared to the incoming request URL and if the URL matches this pattern, it is used by the routing engine to further process the request.

MVC Routing URL Format

To understand the MVC routing, consider the following URL −

http://servername/Products/Phones

In the above URL, Products is the first segment and Phone is the second segment which can be expressed in the following format −

{controller}/{action} 

The MVC framework automatically considers the first segment as the Controller name and the second segment as one of the actions inside that Controller.

Note − If the name of your Controller is ProductsController, you would only mention Products in the routing URL. The MVC framework automatically understands the Controller suffix.

Create a Simple Route

Routes are defined in the RouteConfig.cs file which is present under the App_Start project folder.

MVC Route Config

You will see the following code inside this file −

pubpc class RouteConfig { 
   
   pubpc static void RegisterRoutes(RouteCollection routes) { 
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
      
      routes.MapRoute( 
         name: "Default", 
         url: "{controller}/{action}/{id}", 
         defaults: new { controller = "Home", action = "Index", 
            id = UrlParameter.Optional } 
      ); 
   } 
} 

This RegisterRoutes method is called by the Global.ascx when the apppcation is started. The Apppcation_Start method under Global.ascx calls this MapRoute function which sets the default Controller and its action (method inside the Controller class).

To modify the above default mapping as per our example, change the following pne of code −

defaults: new { controller = "Products", action = "Phones", id = UrlParameter.Optional } 

This setting will pick the ProductsController and call the Phone method inside that. Similarly, if you have another method such as Electronics inside ProductsController, the URL for it would be −

http://servername/Products/Electronics

Advertisements