Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Routing in ASP.NET MVC

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I would like to talk to you about how to understand Routing in ASP.NET MVC. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.

ASP.NET MVC's understanding, let's start with Routing, from the application's point of view, this is absolutely very simple, because the application only needs a few lines of code! So let's understand it from an essential point of view and understand its working mechanism.

Let's start with simplicity:

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

When the application starts, the custom routing information is added to the route collection in RouteTable.

When this is done, the application is over, but it is essentially a beginning, and here I have three questions:

1. What data is in the collection of routes?

The most important thing here is the Route object, because the data we set are all properties of the object, such as Routename and URL..., above, but its function is to construct the RouteData object based on these properties and the request path.

There are two ways to construct a Route object:

1. New Route (...), construct the object, and use RouteTable.Routes.Add (routeObj) to join the collection.

2. RouteCollectionExtensions.IgnoreRoute or MapRoute to construct the Route object and add the collection.

As you can notice, what's the difference between IgnoreRoute and MapRoute? First, take a look at the constructor of Route, which is constructed with a required parameter IRouteHandler:

The IgnoreRoute method constructs StopRoutingHandler as a parameter, while the MapRoute method constructs MvcRouteHandler as a parameter. The difference between the two IRouteHandler is clearly seen in the following code

/ / implementation of MvcRoutingHandler protected virtual IHttpHandler GetHttpHandler (RequestContext requestContext) {return new MvcHandler (requestContext);}

After constructing the Route object, the main use of it is the GetRouteData method, that is, the RouteData object is constructed and obtained according to the HttpContextBase parameters (described below) and the properties in the Route object.

GetRouteDatapublic 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)

2. What role does routing data play in the entire WEB lifecycle?

Now that the data in the collection is clear, let's solve the second problem by taking a look at the life cycle of WEB:

Then, let's take a look at the UrlRoutingModule class, which extends the PostResolveRequestCache and PostMapRequestHandler events, that is, the use for Route is in these two events. let's find out what the event is from the source code.

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

The HttpContextBase object is built when both events are executed, and then passed in as parameters to the following methods. Before processing IHttpHandler, the PostResolveRequestCache method is executed. This method gets RouteData through GetRouteData and IRouteHandler through RouteData's RouteHandler. If it is StopRoutingHandler, the execution is completed, if not, UrlRoutingHandler will be executed.

PostResolveRequestCachepublic 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 executing the IHttpHandler, you need to execute the PostMapRequestHandler method. What this method does is simply to rewrite the request path so that the output path is the same as the input path. Here, the context.Items [] is used to remember the input path, as you can see in the upper and lower sections of code.

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

3. Where and how is the detection done between the requested Url and the Url in the custom Routing?

All we need to know is two actions:

1. Set the Url of the Route object, as shown in the following figure. In the action of setting the Url, you do the following, and set the output ParseRoute object to the internal attribute _ parsedRoute in the Route object.

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

2. RouteData routeData = this.RouteCollection.GetRouteData (context) in the PostResolveRequestCache method, that is, compare with the set Routing according to the requested Url, and get the RouteData. Here, you can see the GetRouteData code above, as shown below:

OK, the understanding of Routing is finished!

After reading the above, do you have any further understanding of how to understand Routing in ASP.NET MVC? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report