Core article--on the core HTTP request Pipeline &&middleware

Source: Internet
Author: User
Tags httpcontext

Directory:

1. Core Processing HTTP request process

2. Middleware (middleware) && process

3. Create custom middleware && simulate core request pipeline

Core Processing HTTP Request Flow

After the HTTP request arrives, it is first received by WebServer (for example, Iis,nginx) and then dropped to Kestrel WebServer, and then kestrel to the. NET core request pipeline after the HTTP request is encapsulated as HttpContext ( Requestdelegate). HttpContext returned response to webserver after a series of middleware.

Middleware (middleware) && process flow

Microsoft's official documentation explains this: the middleware is the component that loads in the application pipeline to process and request accordingly. Each of these components can choose whether the request can be passed to the next component in the pipeline, or it can be executed before or after the next component of the calling pipeline. here is a picture given in the official documentation.

That is, an HTTP request processing process is, through the Middleware 1 processing logic (this time in the middleware 1 to do some processing of HttpContext, such as writing a piece of content), call the next () method, into the middleware 2, repeat the above steps. Eventually, the output of all the middleware's processing logic will be superimposed into the HttpResponse.

There are three ways to call middleware in. NET Core. In the Configure method of startup, the app can be called separately . Use (), app. Run (), app. Map () to invoke the middleware. Let's take a look at the following:

  app. there are two overloaded forms of the Use method:

The first method receives a middleware, and the second method receives a context and a middleware. Let's call the following separately:

1App. Use (next =2             {3                 returnContext =4                 { 5Context. Response.writeasync ("This is middleware1 start ...");6                     returnNext (context);7                 };8             });9App. Use (Async(context, next) =Ten             { One                 awaitContext. Response.writeasync ("This is middleware2 start ..."); A                 awaitnext (); -});

  app. The Run method terminates the pipeline and returns HttpResponse. In our configure method, the last method by default is the app. Run outputs a sentence of HelloWorld, such as

Use and run are relatively simple and are no longer described in detail. Take a look at the results of the program operation:

  app. The Map method is used to build the branch pipeline, which enables a new applicationbuilder. Map matches the branch pipeline based on the requested path. The map method can also match multiple branch pipelines or nested matches according to different pathstring.

            App. Map ("/task", build = =            {                build. Run (async (context) =                {                    await context. Response.writeasync ("This wasmiddleware3 for Map start ...   " );                });            });
1App. Map ("/map", build =2             {3Build. Map ("/maptest2", MapHandleTest2);4Build. Run (Async(context) =5                 {6                     awaitContext. Response.writeasync ("This was middleware3 for Map start ...");7                 });8             });9App. Map ("/maptest1", MapHandleTest1);
1         Private voidMapHandleTest1 (Iapplicationbuilder applicationbuilder)2         {3Applicationbuilder.run (AsyncContext =4             {5                 awaitContext. Response.writeasync ("This was middleware3handletest1 for Map start ...");6             });7         }8         Private voidMapHandleTest2 (Iapplicationbuilder applicationbuilder)9         {TenApplicationbuilder.run (AsyncContext = One             { A                 awaitContext. Response.writeasync ("This was middleware3handletest2 for Map start ..."); -             }); -}

Map also has a special method, Mapwhen, it receives a func

1App. Mapwhen (context = context. Request.Query.ContainsKey ("Branch"),2Build =3Build. Run (AsyncContext =4                     {5                         varBranchver = context. request.query["Branch"];6                         awaitContext. Response.writeasync ($"Branch used = {Branchver}");7                     })8);

, and put a. NET Core middleware

  

Create custom middleware && simulate core request pipeline

The implementation mechanism of pipelines consists of Applicationbuilder and requestdelegate . Requestdelegate is the core of middleware, and the use method adds requestdelegate to the applicationbuilder , Finally, the build method is executed, and all requestdelegate reverse are executed one after the other.

Next, write a custom middleware.

     Public classRequesttestmiddleware {Private ReadOnlyRequestdelegate _next;//The middleware core Requestdelegate,_next represents the execution of the next middleware.          PublicRequesttestmiddleware (requestdelegate next) {_next=Next; }         PublicTask Invoke (HttpContext context) {context. Response.writeasync ("Hello this is my requesttestmiddleware"); return_next (context);//overwrites the delegate Inboke method, passing the HTTP context to the next middleware        }    }     Public Static classrequesttestmiddlewareextensions { Public StaticIapplicationbuilder Userequesttest ( ThisIapplicationbuilder builder)//use the extension method to make our middleware open to the outside.         {            returnBuilder. Usemiddleware<requesttestmiddleware> ();//Add our middleware to the Iapplicationbuilder. }}//Use our custom middleware in startup. App. Userequesttest ();

Simulation construction of HTTP request pipeline

1     /// <summary>2     ///get the request context and return a delegate3     /// </summary>4     /// <param name= "Contex" ></param>5     /// <returns></returns>6      Public DelegateTask requestdelegate (Context contex);7     /// <summary>8     ///simulating the HTTP request context9     /// </summary>Ten      Public classContext One     { A  -}
Requestdelegate and Context
1          Public StaticIlist<func<requestdelegate, requestdelegate>> _list =New2List<func<requestdelegate, requestdelegate>>();3         Static voidMain (string[] args)4         {5Use (next =//Join middleware 16             {7                 returnContext =8                 {9Console.WriteLine ("This was use middleware1");Ten                     returnNext. Invoke (context); One                 }; A             }); -Use (next =//Join Middleware 2 -             { the                 returnContext = -                 { -Console.WriteLine ("This was use middleware2"); -                     returnNext. Invoke (context); +                 }; -             }); +Requestdelegate End = Context = = A             { atConsole.WriteLine ("This is end ...");//Piping -                 returnTask.completedtask;  -             }; - _list. Reverse (); -             foreach(varMiddlewareinch_list) -             { inEnd =Middleware. Invoke (end); -             } toEnd. Invoke (NewContext ());//instantiate an instance of a context + console.readline (); -         } the         /// <summary> *         ///Add middleware to List (Applicationbuilder) $         /// </summary>Panax Notoginseng          Public Static voidUse (Func<requestdelegate, requestdelegate>imiddleware) -         { the _list. ADD (imiddleware); +}
Use middleware and pipe execution

Core article--on the core HTTP request Pipeline &&middleware

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.