I believe that when I first heard this term, some friends would be confused and have many questions. In fact, WHEN I first encountered this concept, I was like everyone else, just like…… such

Next I will explain what the pipeline model is in my own understanding.

  • What is a pipeline model

    First of all has anyone ever thought about. NET WebForm, Mvc, Webapi framework to do application development deployment, the user in the browser or the use of HttpClient input URL address request after how to reach our application? What are the steps in between?

    In fact, after the user enters the URL, the Http request will go through a series of flows, each flow has some unique processing, and the pipeline model is an abstract model to provide support and flows for THE Http request.

  • How does he do it in practice

    The old rule is to figure it out first and then analyze it step by step, just to make it more intuitive, but there are some things before ISAPI that are not marked in the flow chart, which I will mention in the following text, but it is not important.

Next, I will explain the flow chart of a part of the pipeline model in terms of words:

1. The user initiates a request and the request reaches the DNS. The DNS resolves the domain name and finds the corresponding IP address and port. 2.IIS HttpSys listener accepts requests. The HttpSys listener service forwards requests to the appropriate application handler (isapi.dll) based on the request type suffix. The handler mapping can be configured in IIS. Different postfixes map requests to aspnet.isapi, Java, or others The corresponding DLL. 5. Convert the HTTP request to an HttpWorkerRequest object once it reaches Isapi. Then introduced to the HttpRuntime object. The ProcessRequest in function using HttpApplicationFactory incoming HttpContext build HttpApplication, of course in the first few steps if an error occurs, So it just goes straight back.Copy the code

At present, the system preset corresponding part has been executed, because the system is fixed process at this time as a developer and can not be upgraded or expanded, the request to HttpApplication after the real start.

  • HttpApplication

    The HttpApplication class plays an important role in the pipeline model by defining methods, properties, and events that are common to all application objects in an ASP.NET application. This class is the base class for the application defined by the user in the global. asax file. Any HTTP module subscribing to httpApplication events must implement the IHttpModule interface

    Pipeline in our school in the process, should pay attention to is that it had issued a series of events, they used to deal with all kinds of requests, and each request will be executed them one by one again, but as a result of processing is not the same, and may require, so using the event model to expand, content and function of specific events, introduced in the code below.

(The meaning of using events: encapsulate the common part, use the uncertain part of the event, in fact, is the delegate callback, need to extend the part in the form of delegate, more on the delegate content, delegate to C#, as great as Pointers to C, just as impressive)

public class HttpApplication : IComponent,IDisposable, IHttpAsyncHandler, IHttpHandler, IRequestCompletedNotifier, ISyncContext {public Event EventHandler BeginRequest; Public event EventHandler AuthenticateRequest; public event EventHandler AuthenticateRequest; Public event PostAuthenticateRequest; public event PostAuthenticateRequest; Public event AuthorizeRequest; public event AuthorizeRequest; Public event PostAuthorizeRequest; public event PostAuthorizeRequest; Public event ResolveRequestCache; public event ResolveRequestCache; public event ResolveRequestCache; Public event PostResolveRequestCache; public event PostResolveRequestCache; Public event PostMapRequestHandler; public event PostMapRequestHandler; Session public event AcquireRequestState; equeststate = equeststate; equeststate = equeststate; Session public event PostAcquireRequestState; equeststate. Public event PreRequestHandlerExecute; / / has imposed handler public event PostRequestHandlerExecute; Public event ReleaseRequestState; Public event PostReleaseRequestState; public event PostReleaseRequestState; Public event equestcache; Public event PostUpdateRequestCache; public event PostUpdateRequestCache; Public event LogRequest; Public event PostLogRequest; public event PostLogRequest; Public Event EndRequest; }Copy the code
  • HttpModule

    Again, since HttpApplication publishes a series of events, what if I want to extend or customize an event that it publishes? It’s time for HttpModule, and it’s a big part of ASP.NET, because webForms, Mvc, and Even Webapi are just extensions of HttpModule. It’s scary to suddenly feel small and stop learning

It may seem incomprehensible to say this all of a sudden, but as you move on, everything will become clear

Since all events in the HttpApplication are executed for each Http request, and the HttpModule that implements the subscription is executed for each request, global operations such as caching or request compression are appropriate. The following is an example of HttpModule request compression and the steps to implement it

  • 1. First create a class GzipModule that implements the IHttpModule interface
internal class GzipModule : IHttpModule { public void Dispose() { } public void Init(HttpApplication app) { app.BeginRequest += App_BeginRequest; } private void App_BeginRequest(object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; string IsAcceptType = app.Context.Request.Headers["Accept-Encoding"]; If (string.isNulloreMPty (IsAcceptType)) return; IsAcceptType = IsAcceptType.ToUpperInvariant(); // Return the compressed response format if the client request header Contains the compressed request identifier // Return the default response format if (isAcceptType.contains ("GZIP")) { app.Context.Response.AppendHeader("Content-encoding", "gzip"); app.Context.Response.Filter = new GZipStream(app.Context.Response.Filter , CompressionMode.Compress); } else if (IsAcceptType.Contains("DEFLATE")) { app.Context.Response.AppendHeader("Content-encoding", "deflate"); app.Context.Response.Filter = new DeflateStream(app.Context.Response.Filter , CompressionMode.Compress); }}}Copy the code
  • 2. Register HttpModule in the configuration file
		<httpErrors existingResponse="PassThrough" />
          <add name="GzipModule" type="namespace.GzipModule, namespace" preCondition="integratedMode" />
Copy the code

At this point you may be asking if there is a way to dynamically register without writing it in the configuration file. My answer is yes, taking the WebAPI framework as an example

Add a compile feature to AssemblyInfo to dynamically register your code as it is compiled

[assembly: PreApplicationStartMethod(typeof(DynamicRegisterHttpMoudle), "RegisterMoudle")] public class DynamicRegisterHttpMoudle { public static void RegisterMoudle() { HttpApplication.RegisterModule(typeof(GzipModule)); }}Copy the code

2. Use static constructor injection, because the static constructor is called first by the CLR when the class is loaded

    public class WebApiApplication : System.Web.HttpApplication
      static WebApiApplication(){
      protected void Application_Start() { }
Copy the code

You may still not understand HttpModule at this point, but I believe that as you go along, you will have a subversive understanding of it.

  • HttpHandler

    The next important thing to know is HttpHandler, but what is it? The formal answer is this:

    HttpHandler is the real processing center for AN HTTP request, and it's in this HttpHandler container, The ASP.NET Framework actually compiles and executes the server page requested by the client and appends the processed information to the HTTP request flow back to the HttpModule.

    HttpHandler: HttpHandler: HttpHandler: HttpHandler: HttpHandler: HttpHandler: HttpHandler: HttpHandler: HttpHandler: HttpHandler: HttpHandler: HttpHandler: HttpHandler: HttpHandler I’m going to verify this a little bit later, but let’s do a simple implementation of HttpHandler, where we’re going to have our own.cc request handled by our own HttpHandler.

1. First customize the class and then inherit from IHttpHandler

public class CustomHttpHander : IHttpHandler { public bool IsReusable => false; public void ProcessRequest(HttpContext context) { string time =DateTime.Now.ToString(); String respone = string.Format(" custom HttpHander,{0} request arrived ", time); context.Response.Write(respone); }}Copy the code

2. Configure the file to register HttpHandler

<system.webServer> <httpErrors existingResponse="PassThrough" /> <modules> <add name="CustomHttpHandler" path="*.cc" Verb = "*" type = "namespace. CustomHttpHander, namespace preCondition" = "integratedMode, runtimeVersionv4.0" / > < / modules > </system.webServer>Copy the code

So we have a custom.CC request that’s handled by the CustomHttpHandler, and the reason why we have custom request suffixes is that this is the mechanism of HttpHandler, but at its core it’s still an Http request processing center. Of course, we will further understand the MvcHandler, HttpControllerHandler MVC framework of these core handlers, from the point of view of source code to further understand it.

So far, the general concept of the pipeline model and the execution process has been a simple analysis in this article, and the subsequent study of Mvc and Webapi source code because the pipeline and this piece of connection is very close, with this part of the bedding, will be relatively easier to understand.

It may not be good, but if you read it, please click a “like” as encouragement, thank you