MVC Routing Mechanism

Source: Internet
Author: User
Tags classic asp actionlink

The traditional ASP. NET Web Form is supposed to have some kind of association between the URL of the user request and the file above the server, where the server's job is to retrieve the corresponding file to the user based on the received user request. This approach works well in the Web Form era because the ASP. NET page is an ASPX page and is able to respond independently to the user's browser request. However, this approach is inappropriate in MVC, where the user request is handled through the method inside the controller, there is no ASP. NET, one-to-two file association in MVC; To solve this problem, we need to learn the MVC routing mechanism. There are two features of the routing mechanism:1. Check the URL request you received to determine which controller to request which method;2. Generate an external URL (when a user clicks on a link, there is a request to display the URL above the browser via the view)

Now let's start with the MVC routing configuration:

In the MVC framework, there are two ways to create a route:

1. Contract-based routing configuration

2. Specific routing configuration

You may already be familiar with the contract-based routing configuration, but the specific routing configuration is a new addition in MVC5. We're all going to learn here.

The routing mechanism does not know, what is the controller, what is the (Actions) method, it just extracts the URL fragment, the Routing request processing in the subsequent processing, when the routing configuration is satisfied, the requested page can be obtained;

By default, the route matches the URL with the correct fragment, for example {controller}/{action}, which matches a URL with two fragments

The URL pattern is conservative and only matches URLs that have the same fragment, but the URL pattern is inclusive, and as long as the URL has the correct fragment, the value of the fragment is checked, regardless of the value.

The routing configuration is in the RouteConfig.cs file;

 Public Static voidregisterroutes (routecollection routes) {routes. Ignoreroute ("{Resource}.axd/{*pathinfo}"); Routes. MapRoute (Name:"Default", URL:"{Controller}/{action}/{id}", defaults:New{controller ="Home", action ="Index", id =urlparameter.optional}); Routes. MapRoute (Name:"Student", URL:"Student/{id}", defaults:New{controller ="Student", action ="Index"}, Constraints:New{id =@"\d+" }); }

RegisterRoutes This static method is called in the Global.asax file, each time the program runs, the Application_Start () method in the global file is executed, and the routing is registered;
  protected void Application_Start ()        {                        arearegistration.registerallareas ();            Filterconfig.registerglobalfilters (globalfilters.filters);            Routeconfig.registerroutes (routetable.routes);            Bundleconfig.registerbundles (bundletable.bundles);        }

Traditionally, in many web frameworks, such as classic ASP, JSP, PHP, ASP. NET, and so on, the URL represents the physical file on disk.  For example, when you see the request http://example.com/albums/list.aspx, we can determine that the site directory structure contains a albums folder, and there is a list.aspx file under that folder.  This one-to-one relationship between URLs and file systems does not apply to most MVC-based web frameworks, such as ASP. In general, these frameworks use different methods to map URLs to method calls on a class rather than to physical files on disk. In addition, for an MVC application, the first component that the URL request arrives at is the controller, not the view, and the controller does not have a physical path

Overview of routing mechanisms

1. Match the incoming request (the request does not match the file in the server file system) and map these requests to the Controller action (action method in controller)

MVC Basic process: a URL request was made to find the value of the Controller and action, passing the request to the Controller for processing. The controller obtains the model data object and passes the model to view, and the last view is responsible for rendering the page. (plainly, it is a URL to find a method in the controller) (the route is a pattern, there are parameters, through the URL parameters, you can find a way to match this route pattern)

The role of routing:

´url:localhost/home/index´localhost is a domain name, so first remove the domain name section: Home/index´ corresponds to the URL structure in the code above: {Controller}/{action}/{id}´ Because we have established the recognition rules of this URL structure, we can recognize that the controller is home, the action is index, the ID is not the default value "". The routing mechanism is typically composed of route names, route patterns, and default values. Defaults PropertyThe most general routing situation
routes. MapRoute (                "Default",                "{Controller}/{action}/{id}  ",                new"Home""   Globalindex", id = urlparameter.optional}            );

Route URL Pattern

Default value

Matching instances of the URL pattern

{Controller}/{action}/{id}

New {id= ""}

/albums/display/123

/albums/display

{Controller}/{action}/{id}

New {controller= "Home",

action= "Index",

Id= ""}

/albums/display/123

/albums/display

/albums

/

if a URL matches, it's going to go wrong . likeTest has two action in the controller.
Public ActionResult Index ()
Public ActionResult Index (int id)
There is a request in the page Test/index or TEST/INDEX/3 will make an error: The current request for the operation "Index" of the controller type "TestController" is ambiguous between the following methods of operation:
Type MVCDemo.Controllers.TestController of System.Web.Mvc.ActionResult Index ()
Type MVCDemo.Controllers.TestController System.Web.Mvc.ActionResult Index (Int32) because in this most general case, this URL can match two routes, with two methods. In other words, a URL has been sent to the controller to find two methods can be used. This is why the Controller method cannot be overloaded Order of registered routesWhen a URL request arrives at the application, the routing engine iterates through all the registered routes, checks to see if the request URL matches the URL pattern, and then verifies that the retrieved URL parameter is valid based on the specified constraint. Once the routing engine finds the first matching route, it stops traversing. ´ Therefore, the order in which the routes are registered is important and must be registered in the most special to most General order.
Routes. MapRoute ("Showblogroute",               "Blog/post/{id}",                New{controller = "CMS", action = "Show", id=""}); Routes. MapRoute ("Blogroute", "blog/{action}/{id}",                New{controller ="CMS", action = "Index", id = ""});routes. MapRoute ("Defaultroute",//Route name                "{Controller}/{action}/{id}",//URL with Parameters                New{controller ="Home", action ="Index", id = ""}//parameter Default value            ); 

When Url/blog/post/3 arrives at the application, the routing engine begins to evaluate the routing list and stops evaluating the route because the URL matches the first parameter route. If you register the route in reverse order, the URL will match the default route, calling the Post method in BlogController, and you will obviously not get the results you want. when the controller portion of the routing pattern is written {Controller}, can match any of the controllers in the URL section, when it is a blog, can only match blog/... The Routing Constraints PropertyThe Constraints property is a dictionary that contains validation rules for URL parameters, meaning that it is used to define constraints for each parameter's rule or type of HTTP request, such as the following example, if you want to specify the date in the correct format (only numeric values are allowed)
Routes. MapRoute (" Simple",                "Archive/{year}/{month}/{day}",                New{controller="Blog", action="Search", year=" the", month="Ten", day="Ten"},                New{ Year=@"\d{2}|\d{4}",//can only be two-bit or four-bit digitsMonth=@"\d{1,2}",//only one or two digits can be usedday=@"\d{1,2}"//only one or two digits can be used});

2. Constructs an outgoing URL to respond to actions in the controller

Call a method, such as Html.ActionLink or url.action, in a view. This method calls RouteCollection. GetVirtualPath method, the incoming parameter is used to select the URL that is generated for the correct route.

<div>        @Html. ActionLink (" tap ","Click", " Home " );     </div>

RouteCollection. GetVirtualPath method

The return value type is Virtualpathdata, which contains information about the URL path associated with the route.

Two overloaded functions are defined

Method

Description

GetVirtualPath (RequestContext, RouteValueDictionary)

Returns information about the URL path associated with the route, if it has the specified context and parameter values.

GetVirtualPath (RequestContext, String, RouteValueDictionary)

Returns information about the URL path associated with the named route, if it has the specified context, route name, and parameter value.

The first method obtains some information about the current route and a user-specified route value (dictionary) to select the destination route.

1. The routing system then loops through the entire routing table, asking each route through the GetVirtualPath method: "Can you generate a URL given these parameters?"

2. If the answer is yes, then a Virtualpathdata instance is returned, including the URL and some other information related to the match. If the answer is no, a null is returned, and the routing system moves to the next route until the entire routing table is traversed.

Example:

If we define a system in the routing mechanism

routes. MapRoute (Name:"Test", URL:"Test/look/{id}", defaults:New{controller ="Home", action ="Click", id =urlparameter.optional}); Routes. MapRoute (Name:"Default", URL:"{Controller}/{action}/{id}", defaults:New{controller ="Home", action ="Index", id =urlparameter.optional});

Write in the view:

<div>        @Html. ActionLink (" test ","look", " Test " );     </div>   <div>        @Html. ActionLink (" click "," Click ","Home");     </div>

The end result is that no matter which button is clicked, the method is triggered click

 Public class Homecontroller:controller    {        //        // GET:/home/         Public actionresult Index ()        {            return  View ();        }          Public actionresult Click ()        {            return  View ();        }    }

But the URLs that are displayed are

If we enter Test/look or Home/click directly in the address bar, it is correct.

MVC Routing Mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.