MVC source code parsing, mvc source code

Source: Internet
Author: User

MVC source code parsing, mvc source code

From the analysis of the previous chapter, we can see that the IHttpModule can register many, and can also be viewed from the web. config registration, which can be dynamically registered. however, there is a key Module that is not mentioned. Here we will first talk about this key Module-UrlRoutingModule

[TypeForwardedFrom("System.Web.Routing, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]public class UrlRoutingModule : IHttpModule{    // Fields    private static readonly object _contextKey;    private static readonly object _requestDataKey;    private RouteCollection _routeCollection;    // Methods    static UrlRoutingModule();    [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]    public UrlRoutingModule();    protected virtual void Dispose();    protected virtual void Init(HttpApplication application);    private void OnApplicationPostResolveRequestCache(object sender, EventArgs e);    [Obsolete("This method is obsolete. Override the Init method to use the PostMapRequestHandler event.")]    public virtual void PostMapRequestHandler(HttpContextBase context);    public virtual void PostResolveRequestCache(HttpContextBase context);    [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]    void IHttpModule.Dispose();    [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]    void IHttpModule.Init(HttpApplication application);    // Properties    public RouteCollection RouteCollection { get; [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] set; }}

Let's take a look at his Init method and register something.

protected virtual void Init(HttpApplication application){    if (application.Context.Items[_contextKey] == null)    {        application.Context.Items[_contextKey] = _contextKey;        application.PostResolveRequestCache += new EventHandler(this.OnApplicationPostResolveRequestCache);    }}

From the event diagram in the previous article, we can see that this event is registered on the end of the cache check. before reading the registration method, you need to talk about something else. because the Application_Start method is executed before this method is executed. In this method, we create a route table. matched routing rules are added to the routing table.

Let's talk about route registration first.

1. Route Registration

Route registration here is divided into general reason registration, regional route registration, api route registration. Here we only introduce general route registration, which is actually the same, but the registration rules are different.

In Application_Start method, route registration is the following sentence.

RouteConfig.RegisterRoutes(RouteTable.Routes);

Let's take a look at the parameters of this method.

// Abstract: // stores the URL route of the application. [TypeForwardedFrom ("System. Web. Routing, Version = 3.5.0.0,
Culture = Neutral, PublicKeyToken = 31bf3856ad364e35 ")] public class RouteTable {// Abstract: // initialize a new instance of the System. Web. Routing. RouteTable class. Public RouteTable (); // Abstract: // gets a set of objects derived from the System. Web. Routing. RouteBase class. //// Return result: // contains the objects of all routes in the set. Public static RouteCollection Routes {get ;}}

It can be seen from this that it actually transmits a static Route Set and encapsulates it into a route table.

Next, let's take a look at this method.

Public static void RegisterRoutes (RouteCollection routes) {routes. ignoreRoute ("{resource }. axd/{* pathInfo} "); routes. mapRoute (name: "Default", url: "{controller}/{action}/{id}", defaults: new {controller = "Home", action = "Index ", id = UrlParameter. optional}, constraints: new {controller = @ "^ \ w + $", id = @ "^ \ d + $"} // you can leave it empty, here is the constraint on names and parameters );}

The IgnoreRoute here will not be viewed. You can directly look at the MapRoute method. This method is stored in the static extension class: RouteCollectionExtensions

There are a lot of reloads in it. I just want to see the method with the most parameters.

public static Route MapRoute(this RouteCollection routes, string name, string url, 
                    object defaults, object constraints, string[] namespaces){ if (routes == null) { throw new ArgumentNullException("routes"); } if (url == null) { throw new ArgumentNullException("url"); } Route item = new Route(url, new MvcRouteHandler()) { Defaults = CreateRouteValueDictionary(defaults), Constraints = CreateRouteValueDictionary(constraints), DataTokens = new RouteValueDictionary() }; if ((namespaces != null) && (namespaces.Length > 0)) { item.DataTokens["Namespaces"] = namespaces; } routes.Add(name, item); return item;}

Here is the resolution parameter, and the route is created and saved to the route set, that is, saved to the route table.

1. Here is a MvcRouteHandler. The name seems to be somewhat related to MVC. How can I go in?

public class MvcRouteHandler : IRouteHandler{    // Fields    private IControllerFactory _controllerFactory;    // Methods    public MvcRouteHandler();    public MvcRouteHandler(IControllerFactory controllerFactory);    protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext);    protected virtual SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext);    IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext);}

There are exciting things in this GetHttpHandler. Let's take a look at it first. I will not continue to explain it.

protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext){    requestContext.HttpContext.SetSessionStateBehavior(this.GetSessionStateBehavior(requestContext));    return new MvcHandler(requestContext);}

 

2. Why are both ults AND constraints saved as the CreateRouteValueDictionary type? For the moment, I only want to see where it is stored.

private static RouteValueDictionary CreateRouteValueDictionary(object values){    IDictionary<string, object> dictionary = values as IDictionary<string, object>;    if (dictionary != null)    {        return new RouteValueDictionary(dictionary);    }    return new RouteValueDictionary(values);}
public RouteValueDictionary(object values){    this._dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);    this.AddValues(values);} 

Here, ults, constraints, and DataTokens are of the same type.

Wait until you want to use it later.

This article is hooked up with MVC, And the next article officially enters the MVC link analysis.

Directory synchronized

Related Article

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.