Practice ASP. net mvc helps understand Routing

Source: Internet
Author: User

ASP. net MVC understanding, let's start with routing, from the application perspective, this is absolutely very simple, because the application only needs a few lines of code! Therefore, let us understand its working mechanism from an essential perspective.

Let's start with a simple process:

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
"Default",                                              // Route name
"{controller}/{action}/{id}",                           // URL with parameters
new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);
}


protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}

When the application starts, add the custom route information to the route set of the routetable.

After the compilation, the application is finished, but in essence it is only the beginning. Here I have three problems:

1. What data is contained in the routing set?

MVC helps understand routing (figure 1) "src =" http://www.qqread.com/ArtImage/20090313/pi25_1.gif "width =" 567 "Height =" 198 ">

The most important here is the route object, because the data we set is used as the property of this object, for example, the above routename, URL ..., however, it is used to construct a routedata object based on these attributes and request paths.

There are two ways to construct a route object:

1. New route (...), construct the object, and use routetable. routes. Add (routeobj) to join the set.

2. routecollectionextensions. ignoreroute or maproute to construct a route object and add it to the set.

As you can see, what are the differences between ignoreroute and maproute extensions ?! First, let's look at the route constructor. During the construction, there will be a required parameter iroutehandler:

MVC helps understand routing (Figure 2) "src =" http://www.qqread.com/ArtImage/20090313/pi25_2.gif "width =" 371 "Height =" 165 ">

The ignoreroute method constructs stoproutinghandler as the parameter, while the maproute method constructs mvcroutehandler as the parameter. The differences between the two iroutehandler are clearly seen through the following code,

// Mvcroutinghandler implementation
Protected virtual ihttphandler gethttphandler (requestcontext)
{
Return new mvchandler (requestcontext );
}

// Stoproutinghandler implementation
Protected virtual ihttphandler gethttphandler (requestcontext)
{
Throw new notsupportedexception ();
}

After constructing a route object, the getroutedata method is used to construct and obtain the routedata object based on the attributes of the httpcontextbase parameter (described below) and route object,

GetRouteData
public override RouteData GetRouteData(HttpContextBase httpContext)
{
string virtualPath = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + httpContext.Request.PathInfo;
RouteValueDictionary values = this._parsedRoute.Match(virtualPath, this.Defaults);
if (values == null)
{
return null;
}
RouteData data = new RouteData(this, this.RouteHandler);
if (!this.ProcessConstraints(httpContext, values, RouteDirection.IncomingRequest))
{
return null;
}
foreach (KeyValuePair<STRING, object> pair in values)
{
data.Values.Add(pair.Key, pair.Value);
}
if (this.DataTokens != null)
{
foreach (KeyValuePair<STRING, object> pair2 in this.DataTokens)
{
data.DataTokens[pair2.Key] = pair2.Value;
}
}
return data;
}

2. What role does route data play throughout the Web lifecycle?

If we understand the data in the set, we can solve the second problem. First, let's look at the web lifecycle:

MVC helps understand routing (Figure 3) "src =" http://www.qqread.com/ArtImage/20090313/pi25_3.gif "width =" 570 "> click to view the big picture

Next, let's look at the urlroutingmodule class, which extends the postresolverequestcache and postmaprequesthandler events, that is, the purpose of route is in these two events. let's look at the source code to find out what the event actually exists.

Code
private void OnApplicationPostMapRequestHandler(object sender, EventArgs e)
{
HttpContextBase context = new HttpContextWrapper(((HttpApplication) sender).Context);
this.PostMapRequestHandler(context);
}

private void OnApplicationPostResolveRequestCache(object sender, EventArgs e)
{
HttpContextBase context = new HttpContextWrapper(((HttpApplication) sender).Context);
this.PostResolveRequestCache(context);
}

During the execution of these two events, the httpcontextbase object will be constructed and passed in as a parameter. before ihttphandler is processed, the postresolverequestcache method is executed. this method obtains routedata through getroutedata and iroutehandler through routedata's routehandler. If it is stoproutinghandler, the execution is complete. If not, the execution is urlroutinghandler.

PostResolveRequestCache
public virtual void PostResolveRequestCache(HttpContextBase context)
{
RouteData routeData = this.RouteCollection.GetRouteData(context);
if (routeData != null)
{
IRouteHandler routeHandler = routeData.RouteHandler;
if (routeHandler == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, RoutingResources.UrlRoutingModule_NoRouteHandler, new object[0]));
}
if (!(routeHandler is StopRoutingHandler))
{
RequestContext requestContext = new RequestContext(context, routeData);
IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext);
if (httpHandler == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, RoutingResources.UrlRoutingModule_NoHttpHandler, new object[] { routeHandler.GetType() }));
}
RequestData data2 = new RequestData();
data2.OriginalPath = context.Request.Path;
data2.HttpHandler = httpHandler;
context.Items[_requestDataKey] = data2;
context.RewritePath("~/UrlRouting.axd");
}
}
}

After ihttphandler is executed, you must execute the postmaprequesthandler method. The method is simple, that is, rewrite the Request Path to make the output path the same as the input path, here, context is used to remember the input path. items [], which can be seen in the upper and lower sections of code.

PostMapRequestHandler
public virtual void PostMapRequestHandler(HttpContextBase context)
{
RequestData data = (RequestData) context.Items[_requestDataKey];
if (data != null)
{
context.RewritePath(data.OriginalPath);
context.Handler = data.HttpHandler;
}
}



3. Where can I check between the request URL and the custom routing URL?

We only need to understand two execution actions:

1. Set the route object URL. For example, the following actions are performed in the URL setting action, and the output parseroute object is set to the internal attribute _ parsedroute in the route object.

Url
public string Url
{
get
{
return (this._url ?? string.Empty);
}
set
{
this._parsedRoute = RouteParser.Parse(value);
this._url = value;
}
}

MVC helps understand routing (figure 4) "src =" http://www.qqread.com/ArtImage/20090313/pi25_4.gif "width =" 490 "Height =" 679 ">

2. In the postresolverequestcache method, routedata = This. routecollection. getroutedata (context): Compares the request URL with the set routing and obtains routedata. The preceding getroutedata code is shown as follows:

MVC helps understand routing (figure 5) "src =" http://www.qqread.com/ArtImage/20090313/pi25_5.gif "width =" 447 "Height =" 437 ">

OK. The understanding of routing is finished!

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.