Understanding MVC Routing Configuration

Source: Internet
Author: User
In the previous article, I briefly talked about the underlying operating mechanism of MVC, which can be used as a reference for getting started if you are not familiar with MVC. Next, I begin to introduce the relevant knowledge about URL routing. URL routing is not unique to MVC, but rather it exists independently of MVC (under System.Web.Routing). As a result, URL routing can also serve traditional asp.net applications. I use a simple example to explain the route, adding a new page default.aspx to the "ASP.net MVC application" In our previous section, with the background code as follows:
protected void Page_Load (object sender, EventArgs e)
{
    var originalpath = Request.path;
    HttpContext.Current.RewritePath (Request.applicationpath, false);
    IHttpHandler handler = new Mvchttphandler ();
    Handler. ProcessRequest (httpcontext.current);
    HttpContext.Current.RewritePath (Originalpath, false);

When the request page Default.aspx is executed, the requested path is first rewritten to "/", and the path matches the route {Controller}/{action}/{id}, which is mapped to home/index/according to the Global.asax routing configuration. To output index.aspx content instead of Default.aspx, ask why Default.aspx as a normal asp.net page in an MVC application, rather than translating the request into route execution. It is not possible to use the normal asp.net page in MVC. If not, if one day I want to turn my normal site into an MVC site, I need to do it again. With these questions, we go further to explore how to support the original ASP.net page in MVC. Add the following code in the Application_Start () method in Global.asax:

protected void Application_Start ()
{
    arearegistration.registerallareas ();
    RegisterRoutes (routetable.routes);
     = True;
}

Running Default.aspx again will cause a previous error page (no page found).
The code just added: RouteTable.Routes.RouteExistingFiles = True (default is False), which indicates that MVC enables parsing of an existing Web page, although the same resolution to the route {controller}/{action }/{id}, but could not find the corresponding controller route parameter default.aspx, resulting in an error. Next we add the relevant routing settings to it and add the following code to the Global.asax:

Add routing routes for Default.aspx
. Maproute (
    "Start",
    "Default.aspx",
    new {controller = "Home", action = "Index", id = urlparameter.optional } 
);

Delete or comment out the code in the Default.aspx.cs run again, you will find that the page can be resolved normally. It is important to note that the order of URL routing is critical, and once you find the first matching route, you will not continue to look for the remaining routes. This is because a matching routing start is found, which maps correctly to the view index.aspx under home. In order to understand the matching rules of routing parsing more deeply, we introduce the "Routing matching Monitor". Add the reference "RouteDebug.dll" and register the instrumentation code in Global.asax to detect that the ASP is not enabled and enabled (depending on the routeexistingfiles attribute). NET page parsing two situations.

protected void Application_Start ()
{
    arearegistration.registerallareas ();
    RegisterRoutes (routetable.routes);
    RouteTable.Routes.RouteExistingFiles = true;
    routedebugger.rewriteroutesfortesting (routetable.routes);
}

Routing Monitor chart with no (default) Web page resolution enabled

Enable routing monitor diagram for Web page resolution

From the diagram, we find that when Web page parsing is enabled, it is better to have one route item than not enabled, because it is time to look for a matching route item from the Global.asax. The process is probably like this: First look in the routing table collection, and if a matching route definition is found, the parameters in the route definition are parsed, then the controller/view/parameter information for the parameter map is obtained, and finally the specified view page under the specified controller is positioned for output. Instead, the error page is returned when the corresponding matching route cannot be found.

As mentioned earlier, the basic format of URL routing is: {controller}/{action}/{id}, but there are many variations, and in general, the parts that are not included in {} are treated as constants. For example: the correct mapping of Blog/{action}/{author} should be: Blog/show/miracle, and then for example {Report}/{year}/{month}/{day} mapped to: SALE/2012/5/25. This makes it very good to understand the functionality of the page. Developers generally set the URL route definition through the Application_Start () of the Global.asax file to set the route through the routes property of the static class routetable.

public static void RegisterRoutes (RouteCollection routes)
{
    routes. Ignoreroute ("{resource}.axd/{*pathinfo}");
    Routes. ADD (New Route ("Blog/{action}/{author}", New Blogroutehandler ());
}

protected void Application_Start ()
{
    arearegistration.registerallareas ();
    RegisterRoutes (routetable.routes);
}

We can see that two routing parameters are defined in the route: action and author. When a user sends a URL request http://server/blog/show/miracle, the map is mapped according to the route definition so that the action map is show,author mapped to miracle if the user sends a request http:// Server/blog/add, the URL route will not be processed, but rather as a regular page to the ASP.net application, because the corresponding route is not found and there is no default route. You can also set default values for route parameters while adding URL routes.

public static void RegisterRoutes (RouteCollection routes)
{
    routes. Ignoreroute ("{resource}.axd/{*pathinfo}");
    Routes. ADD (New Route ("Blog/{action}/{author}", New Blogroutehandler ())
    {
       = new RouteValueDictionary
        {
            "action", "Show"},
            {"Author", "Miracle"}}
        }
    });
}

Now the user can send more requests, such as: Http://server/blog will map to Http://server/blog/show/miracle, Http://server/blog/add will map to http:// Server/blog/add, and Http://server/blog/add/miraclehe will map to Http://server/blog/add/miraclehe. A simple summary: if the corresponding routing parameter does not have a fill value, the default value is used, otherwise the corresponding route parameter value is used. Sometimes, in order to accommodate the definition of a class of URLs, you can use the wildcard character (*) to represent it. such as: Blog/query/{*values}, the corresponding mapping can include the following:/blog/query/miracle/2012/05,/blog/query/miracle or/blog/query. You may also need to add constraints to the routing parameters to better satisfy the accuracy of the parameters. Such as:

public static void RegisterRoutes (RouteCollection routes)
{
    routes. Ignoreroute ("{resource}.axd/{*pathinfo}");
    Routes. ADD (New Route ("Blog/{locale}/{year}", New Blogroutehandler ())
    {
        = new RouteValueDictionary
        {
            {' locale ', ' {a-z}{2}-{a-z}{2} '},
            {' year ', @ ' \d{4}}}
        '
    ;
}

The corresponding mapping is:/blog/en-us/2012, and/BLOG/EN-US/2012,/BLOG/EN-US/12 do not meet the requirements. After introducing the relevant knowledge about default values and constraints, let's look at the route class definition, which includes the following properties: Default value defaults, constraint constraints, namespace datatokens, URL routing, and routing handler routehandler. The following is a list of its constructors.

Public Route (string url, Iroutehandler handler);
Public Route (string URL, routevaluedictionary defaults, Iroutehandler handler);
Public Route (string URL, routevaluedictionary defaults, routevaluedictionary constraints, Iroutehandler handler);
Public Route (string URL, routevaluedictionary defaults, routevaluedictionary constraints, RouteValueDictionary Datatokens, Iroutehandler handler);

As you can see, the simplest constructor requires only URL routing and routing handlers, and the most complex contains all the attributes.

var route = new route ("Blog/{action}/{author}", 
                       new RouteValueDictionary {{"Action", "show"}, {"Author", "Miracle"} },
                       new Mvcroutehandler ());

You can add (multiple) routes to the routing collection RouteCollection and maintain a collection of routes through the Routetable.routes property.

public static void RegisterRoutes (RouteCollection routes)
{
    routes. ADD (New Route ("Blog/{action}/{author}", 
                       new RouteValueDictionary {{"Action", "show"}, {"Author", "Miracle"}},
                       new Mvcroutehandler ());
}

You may find that adding a route has Maproute and add two methods, so what's the difference. Maproute is an extension of routecollection, and Ingnoreroute, while add is an instance method, relatively complex to invoke with add (including the 5 attributes mentioned earlier), while Maproute is relatively concise.

public static void RegisterRoutes (RouteCollection routes)
{
    routes. Maproute (
        "Article",//Routing name
        "Blog/{action}/{author}",//URL
        New {controller = "Home" with parameters. Action = "Show", author = "Miracle"} 
    );

A careful friend will find that the route name (optional) is specified in the Maproute. First look at the following generated link (mentioned in the next article):

<%= Html.routelink ("Miracle's Blog", "Article", new {action = "Compose"})%>

This is resolved directly by name when URL routing matches, and you can increase the efficiency of the match without having to specify the default route parameters instead of traversing the match. Another way to optimize routing is to store the most common routes at the top of the routing table (as long as the first one is found, it is no longer sought).

Sometimes, we need to customize the routing constraints (we need to implement the Irouteconstraint match method) to meet more complex routing requirements. Suppose the route is: Blog/miracle/{year}/{month}/{day}. The reference value for the year parameter: 2000~2012,month is: 1~12, Day is: 28, 29, 30, or 31 (depending on the month). Add Yearrouteconstraint classes, Monthrouteconstraint classes, and Dayrouteconstraint classes, respectively. Date Routing constraints

public class Yearrouteconstraint:irouteconstraint {public bool Match (HttpContextBase HttpContext, Route Route, Stri ng parametername, routevaluedictionary values, routedirection routedirection) {if (routedirection = = RouteDir Ection.
            Incomingrequest && parametername.tolower () = "Year"} {var year = 0; if (int. TryParse (values["year").
            ToString (), out of year)} {return year >= && year <= 2012;
        return false;
    return false; } public class Monthrouteconstraint:irouteconstraint {public bool Match (HttpContextBase HttpContext, Route Route , string parametername, routevaluedictionary values, routedirection routedirection) {if (routedirection = = Ro Utedirection.incomingrequest && parametername.tolower () = = "Month") {var month =
            0; if (int. TryParse (values["Month"). TOstring (), out month)} {return month >= 1 && month <= 12;
        return false;
    return false; } public class Dayrouteconstraint:irouteconstraint {public bool Match (HttpContextBase HttpContext, Route Route, String parametername, routevaluedictionary values, routedirection routedirection) {if (routedirection = = Rout
            Edirection.incomingrequest && parametername.tolower () = = "Day") {var month = 0; if (!int. TryParse (values["Month").
            ToString (), out month)) return false;

            if (month <= 0 | | | | month >) return false;
            var day = 0; if (!int. TryParse (values["Day").

            ToString (), out of day) is return false; Switch (month) {case 1:case 3:case 5:case 7:case 8:case 10:casE 12:return Day <= 31;
                Case 4:case 6:case 9:case 11:return Day <= 31;
    Case 2:return Day <= 28;//excluding leap year} return false; }

Next, we can use custom constraints to configure the route.

Configures the custom constraint
routes. Maproute ("Article", "Blog/{year}/{month}/{day}",
                new
                {
                    controller = "blog",
                    action = "Show"
                    , Author = "Miracle", Year
                    = "",
                    month = "", Day
                    = ""
                },
                new 
                {Year
                    = new Yearrouteconstrain T (),
                    month = new Monthrouteconstraint (), Day
                    = new Dayrouteconstraint ()
                });

If you run Http://server/blog/show/miracle/2012/4/31 now, you will be given an error because the date constraint is not met.

Next, I briefly summarize the routing resolution process. when a user enters a URL address to send a request, the UrlRoutingModule class resolves the route in the routing table (routetable) that matches the request, and then distributes the route to the routing handler (Iroutehandler). Together with the RequestContext, it is distributed again to the MVC handler (IHttpHandler), locating the relevant controller and performing the relevant actions to implement the output. the following schematic diagram of the entire process.

Finally, I would mention how to use routing in a traditional Web site (in general, users convert a traditional site into a project migration transition to an MVC site). This includes the following two steps:

1. The common Webformroutehandler class that implements the Iroutehandler interface returns an instantiated object that implements the IHttpHandler interface (virtually any page is a IHttpHandler instance object).

public class Webformroutehandler:iroutehandler
{public
    string virtualpath {get; private set;}
    Initializes the virtual path public
    Webformroutehandler (string virtualpath)
    {this
        . virtualpath = virtualpath;
    }
    Public IHttpHandler Gethttphandler (RequestContext requestcontext)
    {
        //Create instantiated Page object
        var page = Buildmanager.createinstancefromvirtualpath (VirtualPath, typeof (Page)) as IHttpHandler;
        return page;
    }

2. Configure the Global Application Class (Global.asax) to implement a map that routes to the traditional Web form.

Map the traditional web site
routes. ADD ("Show", New Route ("Blog/show/{author}", New Webformroutehandler ("~/pages/show.aspx"));
Routes. ADD ("Compose", New Route ("Blog/compose/{year}/{month}/{day}", New Webformroutehandler ("~/pages/compose.aspx"));

Then add two links to the Default.aspx:

<div>
    <a href= "blog/show/miracle" >blog/show/miracle</a>
    <a href= "blog/compose/2012/" 5/28 ">blog/compose/2012/5/28</a>
</div>

Click on the corresponding link will enter the relevant page. Through the above study, we found that we can set up personalized routing ( source code here to download), but please consider how to verify the security of the mapped page, I will explain in detail in the future chapters.

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.