asp.net routing is part of the asp.net mechanism, first understanding some common classes and objects.
1.RouteBase class.
The core of the routing system is the route object, and each routing registration (different URL pattern) corresponds to a route object, which registers with the same Web application to form a routing table. The static property of the route object stored in the RouteTable class routes indicates that this property returns a RouteCollection object. Here route refers to objects of a type that inherit from an abstract class RouteBase
Public abstract class RouteBase
{
//implementation of routing resolution in the Getroutedata method is to get the routing data public
abstract Routedata getrout Edata (HttpContextBase HttpContext);
The GetVirtualPath method generates a complete virtual path by routing resolution public
abstract Virtualpathdata getvirtualpath (
RequestContext re Questcontext,routevaluedictionary values);
It indicates whether to route an existing physical file, the default is true, that an existing physical file cannot be accessed through a URL, only by routing the registry. Public
bool Routeexistingfiles {get; set;}
}
The
Getroutedata returns a Routedata object that encapsulates the routing data. Routedata has a RouteBase property route that returns the route object that generated this routedata. There are
Datatokens and Values two properties, both of which return RouteValueDictionary objects. RouteValueDictionary is a dictionary that implements the Idictionary<string,objects> interface, which is used to save routing variables. The difference between values and Datatokens is that values are parsed from the request URL; datatokens is a custom variable attached directly to the routing object. The Routedata class also has a very important attribute: Routehandler, which plays an important role in the entire routing system, because the HttpHandler object that is ultimately used to process the request is provided by it to provide
GetVirtualPath returns a Virtualpathdata object. When this method is executed, if the variable in the defined routing template matches the specified list of variables, it replaces the placeholder in the template with the specified route variable value, thus obtaining the virtual path. The generated virtual path and the route object are eventually encapsulated into a Virtualpathdata object as the return value. There is also a parameter in this method, the type is RequestContext.
public class requestcontext { //initialization
A new instance of the system.web.routing.requestcontext class.
public requestcontext (); //httpcontext: An object that contains information about HTTP requests //routedata: An object that contains information about the route that matches the current request public requestcontext (httpcontextbase
Httpcontext, routedata routedata);
// Summary: Get information about HTTP requests.
// returns the result: an object that contains information about the HTTP request. public virtual HttpContextBase HttpContext { get; set;
&NBSP} // Summary: gets information about the requested route.
// returns the result: an object that contains information about the requested route. public virtual routedata routedata { get; set; }
2.Route class
RouteBase is an abstract class, and the route type is the only direct successor to the ASP.net routing system's application programming interface. This class has a URL property that represents the routing template that is bound to the routing object. When the request comes in, it matches the URL attribute in the route object to the requested URL, which is the routing resolution.
The route type has other properties in addition to the core property URL. Constraints sets constraints for variables in the template that are routevaluedictionary and whose key and value are variable names and regular expressions as constraints ; defaults also returns a RouteValueDictionary object that holds the default values defined for the route variable. The route type of Datatokens is used to store additional routing variables that do not participate in routing resolution for the request. But for the Getroutedata and GetVirtualPath methods that invoke the route type, the Datatokens contained in the object contains the route variables that originate from this.
3.RouteTable class
What we call the nature of the routing registration is to create the corresponding route object and add it to the global routing table represented by the routetable static attribute routes. First Look at RouteTable,
public class routetable
{public
static routecollection Routes{get}
}
You can see that routetable returns a RouteCollection object, and it is obvious that the global routing table should be in this object. Next look at the RouteCollection class,
public class routecollection : collection<routebase> { // When we call the following 3 methods, we iterate through each of the route objects in the collection.
For each route object, a method of the same name is invoked //if the method returns a specific routedata or Virtualpathdata object, the object will be used directly as the return value of the method. //that is, whenever a matching route object is encountered, the object will be the return value of the entire method //if each route object returns NULL, Then the whole method returns the null public routedata getroutedata (httpcontextbase
HttpContext); public virtualpathdata getvirtualpath (Requestcontext requestcontext,
routevaluedictionary values); public virtualpathdata getvirtualpath (Requestcontext requestcontext,
string name, routevaluedictionary values); //is used to register a routing template so that the routing system can ignore URLs that have this corresponding pattern public void ignore (
String url); public void ignore (STRING&NBSP;URL,&NBSP;OBJECT&Nbsp;constraints); //routing mapping, a total of 5 overloaded Mappageroute methods //This method is the opposite of the Ignore method, It is used to register a mapping between a path and a routing template, and its essence is to add a Route object to this collection public route mappageroute (string
routename, string routeurl, string physicalfile); public route mappageroute (String routename, string routeurl,
string physicalfile, bool checkphysicalurlaccess); }
When we call the Mappageroute method, it takes the Routename parameter as the registered name of the corresponding route object, which has a property dictionary attribute in the mapping relationship of the route object. So we can get this route object by name. The core of the
4. Routing Registration
Route registration is to create a route object based on the routing rules (routing templates, constraints, defaults, etc.) that are provided and then add to routetable. First look at an example:
public static void registerroutes (RouteCollection Routes) { //Specifies default value var defaults = new routevaluedictionary { { "AreaCode", "010" }, { "Day", "2" &NBSP;
}; //constraints based on regular expressions var constains = new
routevaluedictionary { { "AreaCode", @ "0\d{2,3}" },{"Day", @ "[1-3]"} }; //represents a description of the default value of a variable var dataTokens = new routevaluedictionary { { "defaultcity", "BeiJing" }, { "Defaultdays",
"2" } }; //Registration route routetable.routes.mappageroute ("default", "{
Areacode}/{days} ", " ~/weather.aspx ", false, defaults, constains, datatokens); }
At this point, when we enter LOCALHOST:29323;LOCALHOST:29323/010;LOCALHOST:29323/010/2, the effect is the same. The parsed routing data, such as 010,2, exist inside the routedata.values. Second, if the request URL does not meet the constraints of the supplied regular expression, it cannot match the routed object. In the Constains variable, you can also add constraints to the request mode: {"HttpMethod", New Httpmethodconstraint ("POST")}. The
Book also emphasizes that only if Route.routeexistingfiles is True,route.routeexistingfiles true,route.getroutedata () Returns a Routedata object that matches successfully, Routecollection.getroutedata can return a specific Routedata object, this place I still do not want to understand why this.
5. Generate URLs based on routing rules
ASP. NET routing system has 2 main applications: the separation of URL and physical address by registering route template and physical file path mapping, and the complete URL is generated by registered routing rule, the former is realized by the Getroutedata method of RouteCollection object. The latter is realized by the GetVirtualPath method of the RouteCollection object. Let's take a look at GetVirtualPath this method
//a common parameter RequestContext represents the request context, which is the encapsulation of the Routedata and HTTP contexts. Values represent the route variable Public virtualpathdata getvirtualpath (requestcontext requestcontext) that is used to replace placeholders in the template.
routevaluedictionary values); The name parameter represents the registered name of the routing object that is used specifically in the collection, and is also the first parameter Public virtualpathdata getvirtualpath when the Mappageroute method is invoked ( requestcontext requestcontext, string name, routevaluedictionary values);
When this method is invoked, the method iterates through the entire routing table until it finds a route object that matches the specified route parameters if no route object with the route variable is specified. In particular, the method traverses the GetVirtualPath method of the route object until a specific Virtualpathdata object is returned, and if each method returns NULL, the final method returns NULL.
There are three sources of arguments for this method: the default value defined for the variable in the route object, the variable value provided in the Routedata of the RequestContext object (the values attribute), and the additional value of the variable supplied. The RouteValueDictionary object specified by the values argument, and the three variables have a selection priority from low to high.
Routing in 6.MVC
for asp.net MVC applications, the requested target is no longer a specific physical address, but a method in the controller. The route in MVC is an extension of ASP.net, and the main thing is to define a series of extension methods for the RouteCollection type, which are defined in the Routecollectionextensions class, and the namespaces are SYSTEM.WEB.MVC. Let's take a look at some of the methods in this class
public static class routecollectionextensions { //here is the same principle as the ignore in the RouteCollection class public static void
Ignoreroute (This routecollection routes, string url); public static void ignoreroute (This routecollection routes,
string url, object constraints); //here is the same principle as the Mappageroute in the RouteCollection class, and it has multiple overloads public Static route maproute (this routecollection routes, string name, string
url); public static route maproute (This routecollection routes,
string name, string url, object defaults); }
Because the MVC pattern is a controller, the way the method defines the path, not the mapping between the physical path and the route, the parameters of the Maproute and Ignoreroute methods change. For a request, if the routing table matches, the Getroutedata method of the matched route object is invoked and a specific Routedata object is returned.
7. Area-based routing mappings
for larger-scale Web applications, we can take a regional approach, each of which is a separate subsystem that contains models, views and controller directory structure and configuration files, each area has its own routing rules, based on the area of the route map through the arearegistration type for registration.
public class personnalmangerarearegistration : arearegistration { Public override string areaname { get {
return "Personalmanger"; } public Override void registerarea (arearegistrationcontext context) { context.
Maproute ( "Personnalmanger_default", "personalmanger/{controller}/{action}/ {ID} ", new { action = "Index", &NBSP;ID&NBSP;=&NBSP;URLPARAMETER.OPTIONAL&NBSP}, //Controller Namespace new string
[1] { "Personalmanger" &NBSP;} ); &NBSP;&NBSP;&NBSP;&NBSP}}
Above is an example of what I do, which provides a way to register area routing, and then understand the nature learning arearegistration and AreaRegistrationContext classes. The Arearegistration class is an abstract class that abstracts a read-only property areaname returns the name of the current zone, while an abstract method Registerarea to implement a route registration based on the current area. This class also provides 2 abstract static Registerallareas methods:
public static void Registerallareas ();
public static void Registerallareas (object state);//state represents data passed to a specific arearegistration
When the Registerallareas method is executed, all assemblies that are directly or indirectly referenced by the current Web application are loaded (if not loaded), and the MVC Routing mechanism resolves all the inherited arearegistration classes from those assemblies. The corresponding Arearegistration object is created by reflection, and a AreaRegistrationContext object is created as the area registration context. Different from the general Route registration, the Arearegistration implemented by the regional route registration has some subtle differences, embodied in the generated Datatokens more than 2 attributes, respectively, area and Usenamespacefallback attributes, The area represents the name of the zone, which indicates whether a fallback namespace is required, or FALSE if the display specifies a namespace. The namespace attribute generated by the Arearegistration class is not simply adding a namespace string, but adding a., such as the MyWeb namespace, the property value is myweb.*.