. Net core 2.0 Learning Record (4): use Middleware and simulate the construction of the Middleware (RequestDelegate) pipeline,
. Net Core 2 does not continue to use the pipeline events in the previous asp.net, but develops a new pipeline (Middleware ):
Public class MiddlewareDemo {private readonly RequestDelegate _ next; public MiddlewareDemo (RequestDelegate next) {_ next = next;} public Task Invoke (HttpContext httpContext) {// you can write some required code return _ next here. invoke (httpContext );}}
In the Configure method of Startup, add the UseMiddleware Method to the pipeline.
app.UseMiddleware<MiddlewareDemo>();
If you change _ next. Invoke (httpContext) to Task. CompletedTask, The Added Middleware will not be executed.
public Task Invoke(HttpContext httpContext) { return Task.CompletedTask; //return _next.Invoke(httpContext); }
By viewing the source code of the UseMiddleware method, it is found that it actually calls the Use method of IApplicationBuilder.
The following code simulates the construction of the Middleware (RequestDelegate) pipeline.
To facilitate demonstration, we will create a console project and create a new RequestDelegate delegate class.
public delegate Task RequestDelegate(Context context);
public class Context { }
Class Program {static List <Func <RequestDelegate, RequestDelegate> list = new List <Func <RequestDelegate, RequestDelegate> (); static void Main (string [] args) {Use (next => {return context => {Console. writeLine ("111"); return next. invoke (context) ;};}); Use (next =>{ return context =>{ Console. writeLine ("222"); return next. invoke (context) ;};}); Use (next =>{ return context =>{ Console. writeLine ("333"); return next. invoke (context) ;};}); Build (); Console. read ();} static void Use (Func <RequestDelegate, RequestDelegate> middleware) {list. add (middleware);} static void Build () {RequestDelegate endReq = (context) => {Console. writeLine ("end"); return Task. completedTask;}; list. reverse (); // if it is not reversed, foreach (var middleware in list) {endReq = middleware will be executed first. invoke (endReq) ;}endreq (new Context ());}}
Running result:
If you do not execute next. Invoke (context) in a Use method, you will not execute the subsequent Use of the Use method, which will be changed to the following:
Use(next => { return context => { Console.WriteLine("222"); return Task.CompletedTask; //return next.Invoke(context); }; });
Summary:
This mode is highly scalable. For example, if you want to use MVC in a project, write app. UseMvc to add it. If you use Session, use app. UseSession ().
Both Session and Route are implemented using Middleware.