Routing chapter of ASP. NET MVC Learning

Source: Internet
Author: User
Tags httpcontext

constrained Routing

Above we have a {ID} to capture the parameters, but you also found that it can catch any string and so on, but we sometimes need to limit it, such as let it only enter numbers, then we can use the regular expression to constrain it.

Modify RouteConfig.csas follows:

1 Public     class Routeconfig 2     {3 public         static void RegisterRoutes (RouteCollection routes) 4         {5             Routes. MapRoute (6                 Name: "Default", 7                 URL: "{controller}/{action}/{id}", 8                 defaults:new {controller = "Home", AC tion = "Index", id = urlparameter.optional}, 9                 constraints:new{id = @ "^\d*$"},10                 namespaces:new[] {"Mvcstudy . Controllers "}11"             );         }13     }

We can clearly see that we are constrained by the constraints parameter to enter only numbers, but you can also constrain other parameters in the same way. by HttpMethod = new Httpmethodconstraint ("GET", "POST") you can constrain that route to be accessed only in that way.

If your constraints are not possible above, then the following custom constraints will certainly meet your requirements. Creating a new custom constraint is only necessary to create a class that implements the Irouteconstraint interface, for example, we restrict access only to Google Chrome, create a new filters file, and create a new Myrouteconstraint class, write the following code:

1 public     class Myrouteconstraint:irouteconstraint2     {3 4 public         bool Match (HttpContextBase HttpContext, Route route, String parametername, routevaluedictionary values, routedirection routedirection) 5         {6             return HttpContext.Request.UserAgent.Contains ("Chrome"); 7         }8     }

Then we switch to a different browser to test, we will find the difference (if you use the browser's developer tools or other tools to modify useragent , you can also cross this constraint, such as the Filddler2 tool)

Resolve conflicts with physical paths

When a request is sent to ASP. NET MVC, the physical path file that does not exist in the site is checked, and if it exists, it is returned directly to the physical file. But sometimes we need it to execute a method of the controller instead of returning the physical file directly. Then we need this knowledge. Let's start by creating a new test.html in the root directory of the Web site, where you can write some content and then access it. Then write the following code in the RouteConfig.cs :

1 Public     class Routeconfig 2     {3 public         static void RegisterRoutes (RouteCollection routes) 4         {5             Routes. Routeexistingfiles = true; 6  7             routes. MapRoute (8                 Name: "Default2", 9                 URL: "test.html", ten                 defaults:new {controller = "Home", action = "List"}1 1             );         }13     }

This time we re-refresh the browser, then we can see the result of the controller return, so that we solve the physical path and routing conflict between the problem.

8. Bypassing the routing system

If we have some URL paths that we do not want to pass through the routing system, then we can take advantage of this knowledge.

Here's what's RouteConfig.cs :

1 Public     class Routeconfig 2     {3 public         static void RegisterRoutes (RouteCollection routes) 4         {5             Routes. Ignoreroute ("Webresources.axd{*pathinfo}"); 6  7             routes. MapRoute (8                 Name: "Default2", 9                 URL: "test.html", ten                 defaults:new {controller = "Home", action = "List"}11             );         }13     }

9. Custom Routing System

If the above technology does not solve your problem, then we will describe how to customize the routing system. Custom routing systems only need to inherit routebase and implement two methods, as follows:

(1):getroutedata

(2):GetVirtualPath

Here is a simple example I wrote to determine if the visitor is a mobile device, or if the mobile device is routed to a controller with a prefix of M to process the request, otherwise return NULL to the default route

Processing, the following is my source code:

 1 public class Customroutebase:routebase 2 {3 private list<string> useragent; 4 5 public Cu         Stomroutebase (params string[] useragents) 6 {7 useragent = Useragents.tolist (); 8} 9 10 public override Routedata Getroutedata (HttpContextBase HttpContext) One {routedata rd = new Route Data (This, new Mvcroutehandler ()), and the regex r = new Regex (@ "/(\w+)", regexoptions.ignorecase); tchcollection mc = r.matches (HttpContext.Request.Path); String Agent = HttpContext.Request.UserAgent.ToLower (); + foreach (String item in useragent) + {if (agent. Contains (item)) {if (MC). Count >= 2) {Rd. Values.add ("Controller", "M" + mc[0]. GROUPS[1]. Value.tostring ()); Values.add ("Action", mc[1]. GROUPS[1].        Value.tostring ()); 24             }25 Else26 {Rd. Values.add ("Controller", "Mhome"); Rd.             Values.add ("Action", "Index"),}30 return rd;31}32 }33 return null;34}35 public override Virtualpathdata GetVirtualPath (RequestContext reques Tcontext, routevaluedictionary values) PNs {null;39}40}

Finally we add the custom route (RouteConfig.cs):

1 Public     class Routeconfig 2     {3 public         static void RegisterRoutes (RouteCollection routes) 4         {5             Routes. ADD (New Customroutebase ("iphone", "ipad", "Android")); 6  7             routes. MapRoute (8                 Name: "Default2", 9                 URL: "test.html", ten                 defaults:new {controller = "Home", action = "List"}1 1             );         }13     }

Now you create a new mhome controller and then visit it (it is recommended to use Google Chrome and change the useragent with the developer tools to quickly see the effect).

10. Custom Routing Handlers

You might think that the ASP. NET MVC controller is too cumbersome, compared with some features you would prefer to use a generic handler. But you have to use physical paths and find trouble when you visit, so by learning this section, you will be able to add generic handlers to the route and be highly controllable.

First we must create a new class that implements the Iroutehandler interface:

1 Public     class Donwloadhandler:iroutehandler 2     {3  4         IHttpHandler Gethttphandler ( RequestContext RequestContext) 5         {6             return new Customhandler (); 7         } 8     } 9 public     class Customhan Dler:ihttphandler11     {All public         bool IsReusable14         {$             get {return false;}         }17 public         void ProcessRequest (HttpContext context)             . Response.Write ("Download Model");         }22     }

You can see the above source code, I am directly below a new implementation of the IHttpHandler class, and in Gethttphandler , the instance of the class is returned, Of course, you can also make judgments in this method to handle requests according to the actual situation to different general handlers.

Here's how to add this route handler to the route, where we map to the path of mytest:

1 Public     class Routeconfig 2     {3 public         static void RegisterRoutes (RouteCollection routes) 4         {5             Routes. ADD (New Route ("MyTest", New Donwloadhandler ())); 6  7             routes. MapRoute (8                 Name: "Default2", 9                 URL: "test.html", ten                 defaults:new {controller = "Home", action = "List"}11
   );         }13     }

Then we visit http://localhost:2392/MyTest to see the results.

Load: http://www.cnblogs.com/yaozhenfa/

Routing chapter of ASP. NET MVC Learning

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.