MVC source code analysis, mvc source code
In the previous article, we talked about route event registration and route table generation. We also resolved the establishment of pipeline events. Next, we will definitely call and execute these events, and these events will not be displayed, I have obtained the desired part. Next, when executing these pipeline events, the method registered by UrlRoutingModule will be executed. next, let's take a look at what this event has done.
I. OnApplicationPostResolveRequestCache Method
private void OnApplicationPostResolveRequestCache(object sender, EventArgs e){ HttpApplication application = (HttpApplication) sender; HttpContextBase context = new HttpContextWrapper(application.Context); this.PostResolveRequestCache(context);}
The PostResolveRequestCache method of UrlRoutingModule is called here.
Public virtual void PostResolveRequestCache (HttpContextBase context ){
// Query the matched RouteData routeData = this. RouteCollection. GetRouteData (context); if (routeData! = Null ){
// The IRouteHandler returned here is actually mentioned in MvcRouteHandler (previous ).
// In this MvcRouteHandler, there is a method that is used to return IHttpHander. In fact, it is actually the returned MvcHandler IRouteHandler routeHandler = routeData. routeHandler; if (routeHandler = null) {throw new InvalidOperationException (string. format (CultureInfo. currentCulture,
SR. GetString ("UrlRoutingModule_NoRouteHandler"), new object [0]);}
// When registering a route, if it is registered in Ignore mode, StopRoutingHandler if (! (RouteHandler is StopRoutingHandler )){
// Here, the Request context RequestContext requestContext = new RequestContext (context, routeData); context. Request. RequestContext = requestContext;
// Obtain the MVC processing interface here, that is, MvcHandler IHttpHandler httpHandler = routeHandler. getHttpHandler (requestContext); if (httpHandler = null) {throw new InvalidOperationException (string. format (CultureInfo. currentUICulture,
SR. GetString ("UrlRoutingModule_NoHttpHandler"), new object [] {routeHandler. GetType ()});} if (httpHandler is UrlAuthFailureHandler) {if (! FormsAuthenticationModule. FormsAuthRequired) {throw new HttpException (0x191, SR. GetString ("updated");} UrlAuthorizationModule. ReportUrlAuthorizationFailure (HttpContext. Current, this);} else {
// Save MvcHandler to the _ remapHandler attribute of the HttpContext object. context. RemapHandler (httpHandler );}}}}
In order, check the method marked with red above.
1. GetRouteData () method
//RouteCollection
public RouteData GetRouteData(HttpContextBase httpContext){ if (httpContext == null) { throw new ArgumentNullException("httpContext"); } if (httpContext.Request == null) { throw new ArgumentException(SR.GetString("RouteTable_ContextMissingRequest"), "httpContext"); } if (base.Count != 0) { bool flag = false; bool flag2 = false; if (!this.RouteExistingFiles) { flag = this.IsRouteToExistingFile(httpContext); flag2 = true; if (flag) { return null; } } using (this.GetReadLock()) { foreach (RouteBase base2 in this) { RouteData routeData = base2.GetRouteData(httpContext); if (routeData != null) { if (!base2.RouteExistingFiles) { if (!flag2) { flag = this.IsRouteToExistingFile(httpContext); flag2 = true; } if (flag) { return null; } } return routeData; } } } } return null;}
Next, we call the GetRouteData () method of the Route class.
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;}
Here, we will match the route according to the restrictions of the previously registered route. The route that finally matches will be returned.
2. GetHttpHandler () method
The GetHttpHandler method of MvcRouteHandler will be called here, as mentioned in the previous chapter.
protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext){ requestContext.HttpContext.SetSessionStateBehavior(this.GetSessionStateBehavior(requestContext)); return new MvcHandler(requestContext);}
Returns an MvcHandler.
3. RemapHandler () method
The RemapHandler method of HttpContext will be called here.
public void RemapHandler(IHttpHandler handler){ this.EnsureHasNotTransitionedToWebSocket(); IIS7WorkerRequest request = this._wr as IIS7WorkerRequest; if (request != null) { if (this._notificationContext.CurrentNotification >= RequestNotification.MapRequestHandler) { throw new InvalidOperationException(SR.GetString("Invoke_before_pipeline_event",
new object[] { "HttpContext.RemapHandler", "HttpApplication.MapRequestHandler" })); } string handlerType = null; string handlerName = null; if (handler != null) { Type type = handler.GetType(); handlerType = type.AssemblyQualifiedName; handlerName = type.FullName; } request.SetRemapHandler(handlerType, handlerName); } this._remapHandler = handler;}
The last sentence is used to store mvchandler into HttpContext. _ remapHandler.
Here, we can see the process of routing matching and obtain the mvc Processing Program (this is the entrance ).
Ii. route matching
When analyzing a route, you can use a plug-in: RouteDebugger to obtain the route by running the following command on the vs package console:
PM> Install-Package routedebugger
After the configuration is completed, the program automatically adds the following configuration in web. config:
<add key="RouteDebugger:Enabled" value="true" />
We only need to run the program directly. Let's take a look at it first:
In the figure, we can clearly see which route in the matching process can match and which cannot match.
Two minor issues:
If two matching rules are the same but the route name is different, which one will match?
If one is registered in the previous step, the matching will be returned, and the following will not continue to match.
Will there be different matching rules, but the routing name is the same?
Generally, key uniqueness must be ensured when key is used. The same is true for routing. The route name cannot be repeated and must be unique. Otherwise, an error is reported.
If you are interested, you can try it out.
Directory synchronized