How to request access to ASP.net MVC framework _ Practical Tips

Source: Internet
Author: User

First, the preface

For WebForm Development, a request is usually a URL that ends with an. aspx, corresponding to a physical file, which, from the code's point of view, is actually a control (Page). In MVC, a request corresponds to an action in a controller. Familiar with asp.net friends know that the asp.net request is actually to the HttpHandler processing (Implementation of the IHttpHandler type). either. Aspx,.ashx,.asmx or an action in MVC, the request will be given to HttpHandler. Specifically in the pipe event, a HttpHandler is created on request and the PR method is executed. Both ASPX and ASHX are well understood because they themselves implement the IHttpHandler interface, and MVC controller and action are not related to HttpHandler, how is it implemented? Next we'll see how a request enters the MVC framework.

Second, examples

WebForm and MVC are built on the ASP.net platform, WebForm appears earlier, so how does MVC achieve expansion without impacting the underlying framework? This mainly benefits from the ASP.net routing mechanism. The routing mechanism does not belong to Mvc,webform or it can be used. It is designed to separate a request from a physical file by mapping the relationship to map the request to the specified HttpHandler. For example, we can also map a/admin/user.aspx?name= John request to a more readable/admin/John. The following are the ways to register two URLs:

public static void RegisterRoutes (RouteCollection routes)
{
  //mvc
  routes. Maproute (
    name: "Default",
    URL: "{controller}/{action}/{id}",
    defaults:new {controller = "Home", action = "Index", id = urlparameter.optional}
  );
 
  WebForm
  routes. Mappageroute (
    routename: "WebForm",
    routeurl: "Admin/{user}",
    physicalfile: "~/admin/user.aspx"
  );
}

RouteCollection is a route collection that encapsulates routing-related information such as name, URL pattern, constraints, default values, and so on. Among them, Mappageroute is a routecollection defined method, and Maproute is expanded by MVC (the benefit of extending the method is that you can add the required functionality without modifying the original code). Their purpose is the same, create a route object, add to the collection, we can also new a route object, and then call Routecollection.add, the effect is the same. Here we focus on the implementation of the MVC process, WebForm is actually similar.

Third, the analysis of the source

Next we look at how MVC uses the routing mechanism to implement the extensions. Routing mechanism is done through a urlroutingmodule, it is a implementation of the IHttpModule class, the routing module has been the default to help us register well. HttpModule participates in the pipeline processing request by registering the HttpApplication event, specifically subscribing to a phase of the HttpApplication event. Routing mechanism is to use this principle, UrlRoutingModule subscribe to Postresolverequestcache event, implement URL mapping. Why is it the case? Because the next step in the event is to complete the mapping of the request and the physical file, you must intercept this before. The core code is as follows:

public class Urlroutingmodule:ihttpmodule {public routecollection routecollection {get {if (_routecollec
      tion = = null) {//global routecollection Set _routecollection = Routetable.routes;
    return _routecollection;
    } set {_routecollection = value; } protected virtual void Init (HttpApplication application) {//Register Postresolverequestcache event application.
  Postresolverequestcache + = Onapplicationpostresolverequestcache; } private void Onapplicationpostresolverequestcache (object sender, EventArgs e) {//create context HttpApplication app
    = (HttpApplication) sender; HttpContextBase context = new Httpcontextwrapper (app.
    context);
  Postresolverequestcache (context);  public virtual void Postresolverequestcache (HttpContextBase context) {//1. Get routedata Routedata routedata =
    Routecollection.getroutedata (context);
    if (Routedata = = null) {return; //2. Get Iroutehandler Iroutehandler Routehandler = Routedata.routehandler; if (Routehandler = = null) {}//requestcontext guarantees HttpContext and Routedata in subsequent use of RequestContext requ
 
    Estcontext = new RequestContext (context, routedata); Context.
 
    Request.requestcontext = RequestContext;
 
    3. Acquisition of IHttpHandler IHttpHandler HttpHandler = Routehandler.gethttphandler (RequestContext); Remap to handler context.
  Remaphandler (HttpHandler);  
 }
}

We focus on the main approach Postresolverequestcache, which has three key steps.

Step one. Get Routedata

Routedata is the packaging for route, which is used in subsequent processing. Its acquisition is obtained through RouteCollection, which is the same collection object as the routetable.routes used in the above registration. The getroutedata that calls RouteCollection iterates through each of its entries, which is the route object, and then invokes the Getroutedata method of the route object (which is used by many collections within MVC). The following code:

Public Routedata Getroutedata (HttpContextBase HttpContext) {
  using (Getreadlock ()) {
    foreach (routebase route In this) {
      routedata routedata = route. Getroutedata (HttpContext);
      if (routedata!= null) {return           
        routedata
      }
  }} return null;
}

The Getroutedata method for the route object is as follows:

public override Routedata Getroutedata (HttpContextBase HttpContext) {
  string requestpath = HttpContext.Request.AppRelativeCurrentExecutionFilePath.Substring (2) + HttpContext.Request.PathInfo;
 
  Combined with default values, matching urls
  routevaluedictionary values = _parsedroute.match (Requestpath, Defaults);
 
  if (values = = null) {return
    null;
  }
 
  Packaged into Routedata, why not put it behind the IF?
  routedata routedata = new Routedata (this, routehandler);
 
  Match constraint
  if (! Processconstraints (HttpContext, Values, Routedirection.incomingrequest)) {return
    null;
  }
 
  Routedata values and Datatokens are all derived from Route
  foreach (var value in values) {
    routeData.Values.Add (value). Key, value. Value);
  }
  if (datatokens!= null) {
    foreach (var prop in Datatokens) {
      routedata.datatokens[prop. Key] = Prop. Value;
    }
  }
 
  return routedata;
}

As you can see, the Getroutedata method of the route object matches the URL pattern, and checks for constraints, and returns NULL if it does not conform. If it matches, the new one routedata.

Step two, get the Iroutehandler interface object

The Routedata is created above, and the parameters are the current route object and its Routehandler property. Routehandler is a iroutehandler, which is an important interface, and it is defined as follows:

Public interface Iroutehandler {
  IHttpHandler gethttphandler (RequestContext requestcontext);
}

Obviously, it is used to get IHttpHandler. So where is the Routehandler property of the route object initialized? We go back to the beginning of the registration method, routes. Maproute, this method creates a route object based on the parameters passed, which is implemented as follows:

public static Route Maproute (this routecollection routes, string name, string URL, object defaults, object constraints, St Ring[] namespaces
{
  //Create a Route object with Iroutehandler mvcroutehandler Route
  = new Route (URL, new Mvcroutehandler ())
  {
    Defaults = createroutevaluedictionary (Defaults),
    Constraints = Createroutevaluedictionary (constraints),
    datatokens = new RouteValueDictionary ()
  };
 
  if (namespaces!= null) && (namespaces. Length > 0))
  {
    route. Datatokens["namespaces"] = namespaces;
  }
 
  Register the route in the RouteCollection
  routes. ADD (name, route);
 
  return route;
}

When creating route, in addition to passing the URL pattern, the default helps us pass a mvcroutehandler, which implements the Iroutehandler interface.
step three, get the IHttpHandler interface object

With Mvcroutehandler, you can call its Gethttphandler method to get IHttpHandler, which implements the following:

Protected virtual IHttpHandler Gethttphandler (RequestContext requestcontext)
{
  //Set session state
  RequestContext.HttpContext.SetSessionStateBehavior (Getsessionstatebehavior (RequestContext));
 
  Returns a Mvchandler return
  new Mvchandler (RequestContext) that implements the IHttpHandler;

As you can see, it returns a Mvchandler,mvchandler and implements the IHttpHandler interface. So the beginning of said, the request essence is to HttpHandler, in fact, MVC is the case, the request to the Mvchandler processing. We can look at Mvchandler definitions and main methods:

public class Mvchandler:ihttpasynchandler, IHttpHandler, irequiressessionstate {protected internal virtual Iasyncre Sult BeginProcessRequest (HttpContextBase HttpContext, AsyncCallback callback, object state) {IController Controller
    ;
 
    Icontrollerfactory Factory;
 
    This method activates the Controller object Processrequestinit (HttpContext, out controller, out factory);
    Iasynccontroller Asynccontroller = controller as Iasynccontroller; if (Asynccontroller!= null) {//Asynchronous controller Begininvokedelegate Begindelegate = delegate (Asy
          Nccallback AsyncCallback, Object asyncstate) {try {//Call Controller BeginExecute method
        Return Asynccontroller.beginexecute (RequestContext, AsyncCallback, asyncstate); Catch {factory.
          Releasecontroller (Asynccontroller);
        Throw
 
      }
      };
    Endinvokedelegate enddelegate = delegate (IAsyncResult asyncresult) {try    {Asynccontroller.endexecute (asyncresult); finally {factory.
        Releasecontroller (Asynccontroller);
 
      }
      };
      SynchronizationContext Synccontext = Synchronizationcontextutil.getsynchronizationcontext ();
      AsyncCallback newcallback = Asyncutil.wrapcallbackforsynchronizedexecution (callback, Synccontext);
    Return to Asyncresultwrapper.begin (Newcallback, State, Begindelegate, Enddelegate, _processrequesttag); else {//synchronous Controller Action action = delegate {try {Co Ntroller.
        Execute (RequestContext); finally {factory.
        Releasecontroller (Controller);
 
      }
      };
    Return Asyncresultwrapper.beginsynchronous (callback, State, action, _processrequesttag);
 }
  }
}

As you can see, the Mvchandler task is to activate the controller and execute its Execute method. This process is very similar to the page processing in WebForm, where the. aspx request arrives, and the page that implements IHttpHandler is found based on the virtual path (similar to the routing mechanism found mvchandler based on the URL pattern). It then enters the page cycle (similar to the activation controller of MVC, and then executes the action process).

Iv. Summary

Next, briefly summarize the process of requesting access to the MVC framework:

1. Add the Routing object route to the global Routecollection,route Iroutehandler initialized to Mvcroutehandler.

2. UrlRoutingModule registers the HttpApplication Postresolverequestcache event, realizes requests to intercept.
3. Request arrives, traverse routecollection in the processing event, call each route object Getroutedata get Routedata wrapper object.

4. Call the Mvcroutehandler Gethttphandler to get the Mvchandler.

5. The remaphandler that calls HttpContext maps the request to the Mvchandler handler.

6. Execute Mvchandler PR method, activate controller, execute action.

The above is the entire content of this article, I hope to help you learn.

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.