ASP. NET MVC development experience sharing: Routing and Skills

Source: Internet
Author: User

The ASP. NET MVC preset can easily define the format you wish to have in the RegisterRoutes method of Global.asax, strictly speaking this is not the exclusive interest of ASP. NET MVC, but the new features added from the ASP. 3.5 SP1. So just as the traditional ASP. NET Web Form can take advantage of the good that Routing brings, today I will talk about some Routing's observations and techniques.

Get started quickly

I first explained the Routing code that global.asax in the ASP. NET MVC, which is a place that beginners can easily read.

The following text is used to describe the part of the previous symbol:

  1. The point at which ASP. NET performs is in the HttpApplication Application_Start () method, where all Routing are determined, where routetable.routes is a public a static object, which is used to save all Routing rules, whose object type is routecollection.
  2. The Ignoreroute in the RegisterRoutes method is used to define the Web address Routing .
    Note: The Ignoreroute expansion method is part of ASP. NET MVC (SYSTEM.WEB.MVC).
  3. {Resource} represents a route variable (routevalue) whose name is resource, but it can actually take any name here, which represents only a variable space (PlaceHolder) It's strikes. It always represents a "position" that can be put into an unused variable.
  4. {*pathinfo} also represents a RouteValue name PathInfo, but the name preceding the Star (*) represents the catchall meaning, and this pathInfo will be the complete PATH in FO deduction of the target 3 than the Internet address. For example, if the Web address is/TEST.AXD/A/B/C/D pathInfo The value is A/B/C/D, if the star is not added (*) The pathInfo will be equal to a. And here it can actually take any name, and here it just stands for a change.
  5. The MapRoute is the most commonly used method of defining Routing.
    Note: The MapRoute expansion method is part of ASP. NET MVC (SYSTEM.WEB.MVC).
  6. The definition of the Route name , which is less used, but it is used to develop advanced Routing techniques.
  7. The definition Web format is named for the routevalue of each of the paragraph (Path Segment) of the Web address .
    Note: The Web address cannot be started with a diagonal line (/).
  8. The preset values for the routevalue parameters of the definition

Basic concept

    • Routing (System.Web.Routing) is part of the ASP. NET 3.5 SP1, and ASP. NET MVC is only used
    • Routetable.routes is a public Meditation object that will be fixed for the entire HttpApplication life cycle!
    • Since Routetable.routes is a public Meditation Object , it is possible to adjust the routetable.routes content without having to re-edit the website. Details: Editable Routes and Editable Routes Using App_Code
    • Ignoreroute and MapRoute These two methods of expansion (Extensionmethod) are the expansion methods provided by the new routecollectionextensions category in the SYSTEM.WEB.MVC naming space, for the convenience of writing Routing the rules.
    • In the Routing set, the first criterion of success is directly used, which is similar to the Firewall Rules.

Routing Tips

Tip 1: Set the restrictions on the Routing Web site

Since ASP. NET MVC has a very important feature: to replace the set (Convention over Configuration), so when we go from the network path to the Controller, the routing variables on the site are automatically In the Action method's parameters, for example, we have the following routing definitions in the Global.asax.cs file:

Routes. MapRoute (    "Product",    "Product/{productid}",    new {controller="product", action=" Details "});    

And the content of our Action method is as follows:

Public ActionResult Details (int productId) {    return View ();} 

Because the parameters in the Action method are of type int, the PRODUCTID route variable must be an integer, and if it is not an integer, it will cause the parameters dictionary contains a null entry For parameter ' productId ' of non-nullable type ' System.Int32 ' for method ' System.Web.ActionResult Details (Int32) ' in ... 's mistake happened.

To avoid this kind of inefficient site routing, we can make more restrictive terms in the definition route, in order to step up the format requirements for whether the Web paragraph (pathsegment) conforms to the routing change (RouteValue). We take the example above to modify the routing definition, as in the following example, we added a number of parameters to the MapRoute, where \d+ is a regular expression (RegEx) :

Routes. MapRoute (    "Product",    "Product/{productid}",    new {controller="product", action= "Details"},    @ "\d+"});     

Note: The RegEx style here will automatically help you add ^ start and end, and this will certainly be better than the complete Web paragraph (Path Segment).

In this way, when the format of the Web address is/product/cellphone, it is not comparable to the "Product" routing rule.

Tip 2: Customize Routing condition Restrictions

In general, through the Regex regular formula to define the RouteValue condition limit has been sufficient, but if the need for a more complex judgment, it is possible to customize the Routing condition limit, the custom method is through the actual Irouteconstraint interface to complete the way , the interface has only one Match method that needs to be done, the following is the definition of the method:

BOOL Match (    httpcontextbase HttpContext,    Route route,    string parametername,    routevaluedictionary values,    routedirection routedirection)

With these incoming parameters, you'll be able to get a lot of the information you might get at the time of the site change, and then you can get the information you've got, and you'll have hundreds of different restrictions on how you can write. For example, if you want to set a routing limit (route Constraint) that can only be used when Localhost does a Web site, we can determine whether the source computer is coming from this machine by httpContext.Request.IsLocal, So we can write the following code:

Using System.Web; using System.Web.Routing; namespace Mvcapplication1.constraints {    class Localhostconstraint:irouteconstraint {        return httpContext.Request.IsLocal; } }}

So how do we define the routing rules in Global.asax.cs? Please see the following code:

Routes. MapRoute (    "admin",    "Admin/{action}",    new {controller="admin"},    new {islocal= new Localhostconstraint ()});     

Sharp-eyed people may find that we have used a isLocal variable in place of the restricted conditions, but the change is not present in the Web format , but why is it used? Who is it to limit? Is there really a isLocal this routevalue change?

I believe that beginners are likely to have these questions when they see these codes, because at the time I saw this code was a bit suspicious, in fact, the custom routing restrictions applied in the routing definition, the name of its anonymous variable is not important, all the sentences are written in the code of the custom routing restrictions, So the above routing definition if I change to the following, still can work normally, when you name yourself as long as you feel good remember, understood can:

Routes. MapRoute (    "admin",    "Admin/{action}",    new {controller="admin"},    new { onlylocalhostcanapply=New Localhostconstraint ()});     

Tip 3: Let ASP. NET MVC with ASP. NET Web Form

The operation of ASP. NET-based MVC differs from ASP. NET-Web forms, so normally both of these structures operate normally in a preset manner, and only in certain special settings will they interfere with each other, and when your Web site is deployed, you can apply the following Routing techniques, set specific paths do not walk the line of ASP.

Here are some examples of code that have been discard out of routing rules:

    • Ignore all *.aspx's web address paths
      Routes. Ignoreroute ("{resource}.aspx/{*pathinfo}");
    • Ignore All programs and files that are in the Page catalog (note that this ignores Routing, and it is up to IIS to judge what kind of Handler to use for this HTTP request)
      Routes. Ignoreroute ("Page/{*pathinfo}");
    • Ignore all files in Page catalog (another notation)
      Routes. ADD (new Route (stoproutinghandler())); 

It is also worth noting that Routing's motion is actually a module used to distribute the Request before the HttpHandler is executed, so it is possible to decide after the Routing of the definition and the decision to continue to execute ASP. NET MVC or a Sp.net Web Form, in the IIS7 HTTP Request's execute sequence, the UrlRoutingModule (Routing module) is executed as shown below, and the event name is Resolve Cache after this step (postr Esolverequestcache):

Here are some references to help you learn how to apply the Web page of the ASP. Routing Rules:

    • Using Routing with WebForms
    • URL Routing with ASP. NET 4 Web Forms (VS. and. 4.0 Series)
    • Extreme asp.net-routing with ASP. NET Web Forms

Tip # 4: Let Routing also deal with existing files (all sites are Routing in the right)

When HTTP requirements come in, in the case of ASP. NET Routing, as long as the input network path can be compared to the files in the actual file system, it will skip the Routing system directly, which is why ASP. NET MVC and ASP. NET Web Form One of the reasons for a peaceful common cause is that the ASP. NET Web Form is bound to have an ASPX file (or other file type), and when the HTTP request comes in, it will immediately find a physical file, which will directly skip the ASP. NET Routing machine.

This design is normally done in most environments, but in some special designs you might want to require that all HTTP requirements be Routing by an ASP (for example, if you want to do the rights management with ASP. NET Routing), you can do this at The RegisterRoutes method in the Global.asax.cs file can be combined with the following code:

True

The following images are shown:

This design also brings some side effects, because when you really have a physical file to directly pass through the IIS response, you have to set Ignoreroute or Stoproutinghandler for a particular file type or path (as mentioned in tip 3 of this article).

ASP. NET MVC development experience sharing: Routing and Skills

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.