ASP.NET Core 中间件(Middleware)的使用及其源码解析 -- 系列文章

发布时间 2023-07-19 16:26:50作者: jack_Meng

ASP.NET Core 中间件(Middleware)的使用及其源码解析(一)- 源码解析

中间件是一种装配到应用管道以处理请求和响应的软件。每个组件:

1、选择是否将请求传递到管道中的下一个组件。

2、可在管道中的下一个组件前后执行工作。

请求委托用于生成请求管道。请求委托处理每个 HTTP 请求。

请求管道中的每个中间件组件负责调用管道中的下一个组件,或使管道短路。当中间件短路时,它被称为“终端中间件”,因为它阻止中间件进一步处理请求。

废话不多说,我们直接来看一个Demo,Demo的目录结构如下所示:

本Demo的Web项目为ASP.NET Core Web 应用程序(目标框架为.NET Core 3.1) MVC项目。  

其中 Home 控制器代码如下:

复制代码
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NETCoreMiddleware.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            Console.WriteLine("");
            Console.WriteLine($"This is {typeof(HomeController)} Index");
            Console.WriteLine("");
            return View();
        }
    }
}
复制代码

其中 Startup.cs 类的代码如下:

复制代码
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NETCoreMiddleware
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        //服务注册(往容器中添加服务)
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

        /// <summary>
        /// 配置Http请求处理管道
        /// Http请求管道模型---就是Http请求被处理的步骤
        /// 所谓管道,就是拿着HttpContext,经过多个步骤的加工,生成Response,这就是管道
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            #region 环境参数

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            #endregion 环境参数

            //静态文件中间件
            app.UseStaticFiles();

            #region Use中间件

            //中间件1
            app.Use(next =>
            {
                Console.WriteLine("middleware 1");
                return async context =>
                {
                    await Task.Run(() =>
                    {
                        Console.WriteLine("");
                        Console.WriteLine("===================================Middleware===================================");
                        Console.WriteLine($"This is middleware 1 Start");
                    });
                    await next.Invoke(context);
                    await Task.Run(() =>
                    {
                        Console.WriteLine($"This is middleware 1 End");
                        Console.WriteLine("===================================Middleware===================================");
                    });
                };
            });

            //中间件2
            app.Use(next =>
            {
                Console.WriteLine("middleware 2");
                return async context =>
                {
                    await Task.Run(() => Console.WriteLine($"This is middleware 2 Start"));
                    await next.Invoke(context); //可通过不调用 next 参数使请求管道短路
                    await Task.Run(() => Console.WriteLine($"This is middleware 2 End"));
                };
            });

            //中间件3
            app.Use(next =>
            {
                Console.WriteLine("middleware 3");
                return async context =>
                {
                    await Task.Run(() => Console.WriteLine($"This is middleware 3 Start"));
                    await next.Invoke(context);
                    await Task.Run(() => Console.WriteLine($"This is middleware 3 End"));
                };
            });

            #endregion Use中间件

            #region 最终把请求交给MVC

            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            #endregion 最终把请求交给MVC
        }
    }
}
复制代码

用 Use 将多个请求委托链接在一起,next 参数表示管道中的下一个委托(下一个中间件)。

下面我们使用命令行(CLI)方式启动我们的网站,如下所示:

可以发现控制台依次输出了“middleware 3” 、“middleware 2”、“middleware 1”,这是怎么回事呢?此处我们先留个疑问,该点在后面的讲解中会再次提到。

启动成功后,我们来访问一下 “/home/index” ,控制台输出结果如下所示:

请求管道包含一系列请求委托,依次调用,下图演示了这一过程:

每个委托均可在下一个委托前后执行操作。应尽早在管道中调用异常处理委托,这样它们就能捕获在管道的后期阶段发生的异常。

此外,可通过不调用 next 参数使请求管道短路,如下所示:

复制代码
/// <summary>
/// 配置Http请求处理管道
/// Http请求管道模型---就是Http请求被处理的步骤
/// 所谓管道,就是拿着HttpContext,经过多个步骤的加工,生成Response,这就是管道
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    #region 环境参数

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    #endregion 环境参数

    //静态文件中间件
    app.UseStaticFiles();

    #region Use中间件

    //中间件1
    app.Use(next =>
    {
        Console.WriteLine("middleware 1");
        return async context =>
        {
            await Task.Run(() =>
            {
                Console.WriteLine("");
                Console.WriteLine("===================================Middleware===================================");
                Console.WriteLine($"This is middleware 1 Start");
            });
            await next.Invoke(context);
            await Task.Run(() =>
            {
                Console.WriteLine($"This is middleware 1 End");
                Console.WriteLine("===================================Middleware===================================");
            });
        };
    });

    //中间件2
    app.Use(next =>
    {
        Console.WriteLine("middleware 2");
        return async context =>
        {
            await Task.Run(() => Console.WriteLine($"This is middleware 2 Start"));
            //await next.Invoke(context); //可通过不调用 next 参数使请求管道短路
            await Task.Run(() => Console.WriteLine($"This is middleware 2 End"));
        };
    });

    //中间件3
    app.Use(next =>
    {
        Console.WriteLine("middleware 3");
        return async context =>
        {
            await Task.Run(() => Console.WriteLine($"This is middleware 3 Start"));
            await next.Invoke(context);
            await Task.Run(() => Console.WriteLine($"This is middleware 3 End"));
        };
    });

    #endregion Use中间件

    #region 最终把请求交给MVC

    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "areas",
            pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });

    #endregion 最终把请求交给MVC
}
复制代码

此处我们注释掉了 中间件2 的 next 参数调用,使请求管道短路。下面我们重新编译后再次访问 “/home/index” ,控制台输出结果如下所示:

当委托不将请求传递给下一个委托时,它被称为“让请求管道短路”。 通常需要短路,因为这样可以避免不必要的工作。 例如,静态文件中间件可以处理对静态文件的请求,并让管道的其余部分短路,从而起到终端中间件的作用。 

对于终端中间件,框架专门为我们提供了一个叫 app.Run(...) 的扩展方法,其实该方法的内部也是调用 app.Use(...) 这个方法的,下面我们来看个示例:

复制代码
/// <summary>
/// 配置Http请求处理管道
/// Http请求管道模型---就是Http请求被处理的步骤
/// 所谓管道,就是拿着HttpContext,经过多个步骤的加工,生成Response,这就是管道
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    #region 环境参数

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    #endregion 环境参数

    //静态文件中间件
    app.UseStaticFiles();

    #region Use中间件

    //中间件1
    app.Use(next =>
    {
        Console.WriteLine("middleware 1");
        return async context =>
        {
            await Task.Run(() =>
            {
                Console.WriteLine("");
                Console.WriteLine("===================================Middleware===================================");
                Console.WriteLine($"This is middleware 1 Start");
            });
            await next.Invoke(context);
            await Task.Run(() =>
            {
                Console.WriteLine($"This is middleware 1 End");
                Console.WriteLine("===================================Middleware===================================");
            });
        };
    });

    //中间件2
    app.Use(next =>
    {
        Console.WriteLine("middleware 2");
        return async context =>
        {
            await Task.Run(() => Console.WriteLine($"This is middleware 2 Start"));
            await next.Invoke(context); //可通过不调用 next 参数使请求管道短路
            await Task.Run(() => Console.WriteLine($"This is middleware 2 End"));
        };
    });

    //中间件3
    app.Use(next =>
    {
        Console.WriteLine("middleware 3");
        return async context =>
        {
            await Task.Run(() => Console.WriteLine($"This is middleware 3 Start"));
            await next.Invoke(context);
            await Task.Run(() => Console.WriteLine($"This is middleware 3 End"));
        };
    });

    #endregion Use中间件

    #region 终端中间件

    //app.Use(_ => handler);
    app.Run(async context =>
    {
        await Task.Run(() => Console.WriteLine($"This is Run"));
    });

    #endregion 终端中间件

    #region 最终把请求交给MVC

    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "areas",
            pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });

    #endregion 最终把请求交给MVC
}
复制代码

Run 委托不会收到 next 参数。第一个 Run 委托始终为终端,用于终止管道。Run 是一种约定。某些中间件组件可能会公开在管道末尾运行 Run[Middleware] 方法。

我们重新编译后再次访问 “/home/index” ,控制台输出结果如下所示:

此外,app.Use(...) 方法还有另外一个重载,如下所示(中间件4):

复制代码
/// <summary>
/// 配置Http请求处理管道
/// Http请求管道模型---就是Http请求被处理的步骤
/// 所谓管道,就是拿着HttpContext,经过多个步骤的加工,生成Response,这就是管道
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    #region 环境参数

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    #endregion 环境参数

    //静态文件中间件
    app.UseStaticFiles();

    #region Use中间件

    //中间件1
    app.Use(next =>
    {
        Console.WriteLine("middleware 1");
        return async context =>
        {
            await Task.Run(() =>
            {
                Console.WriteLine("");
                Console.WriteLine("===================================Middleware===================================");
                Console.WriteLine($"This is middleware 1 Start");
            });
            await next.Invoke(context);
            await Task.Run(() =>
            {
                Console.WriteLine($"This is middleware 1 End");
                Console.WriteLine("===================================Middleware===================================");
            });
        };
    });

    //中间件2
    app.Use(next =>
    {
        Console.WriteLine("middleware 2");
        return async context =>
        {
            await Task.Run(() => Console.WriteLine($"This is middleware 2 Start"));
            await next.Invoke(context); //可通过不调用 next 参数使请求管道短路
            await Task.Run(() => Console.WriteLine($"This is middleware 2 End"));
        };
    });

    //中间件3
    app.Use(next =>
    {
        Console.WriteLine("middleware 3");
        return async context =>
        {
            await Task.Run(() => Console.WriteLine($"This is middleware 3 Start"));
            await next.Invoke(context);
            await Task.Run(() => Console.WriteLine($"This is middleware 3 End"));
        };
    });

    //中间件4
    //Use方法的另外一个重载
    app.Use(async (context, next) =>
    {
        await Task.Run(() => Console.WriteLine($"This is middleware 4 Start"));
        await next();
        await Task.Run(() => Console.WriteLine($"This is middleware 4 End"));
    });

    #endregion Use中间件

    #region 终端中间件

    //app.Use(_ => handler);
    app.Run(async context =>
    {
        await Task.Run(() => Console.WriteLine($"This is Run"));
    });

    #endregion 终端中间件

    #region 最终把请求交给MVC

    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "areas",
            pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });

    #endregion 最终把请求交给MVC
}
复制代码

我们重新编译后再次访问 “/home/index” ,控制台输出结果如下所示:

 

下面我们结合ASP.NET Core源码来分析下其实现原理: 

首先我们通过调试来看下 IApplicationBuilder 的实现类到底是啥?如下所示:

可以看出它的实现类是  Microsoft.AspNetCore.Builder.ApplicationBuilder ,我们找到 ApplicationBuilder 类的源码,如下所示:

复制代码
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Internal;

namespace Microsoft.AspNetCore.Builder
{
    public class ApplicationBuilder : IApplicationBuilder
    {
        private const string ServerFeaturesKey = "server.Features";
        private const string ApplicationServicesKey = "application.Services";

        private readonly IList<Func<RequestDelegate, RequestDelegate>> _components = new List<Func<RequestDelegate, RequestDelegate>>();

        public ApplicationBuilder(IServiceProvider serviceProvider)
        {
            Properties = new Dictionary<string, object>(StringComparer.Ordinal);
            ApplicationServices = serviceProvider;
        }

        public ApplicationBuilder(IServiceProvider serviceProvider, object server)
            : this(serviceProvider)
        {
            SetProperty(ServerFeaturesKey, server);
        }

        private ApplicationBuilder(ApplicationBuilder builder)
        {
            Properties = new CopyOnWriteDictionary<string, object>(builder.Properties, StringComparer.Ordinal);
        }

        public IServiceProvider ApplicationServices
        {
            get
            {
                return GetProperty<IServiceProvider>(ApplicationServicesKey);
            }
            set
            {
                SetProperty<IServiceProvider>(ApplicationServicesKey, value);
            }
        }

        public IFeatureCollection ServerFeatures
        {
            get
            {
                return GetProperty<IFeatureCollection>(ServerFeaturesKey);
            }
        }

        public IDictionary<string, object> Properties { get; }

        private T GetProperty<T>(string key)
        {
            object value;
            return Properties.TryGetValue(key, out value) ? (T)value : default(T);
        }

        private void SetProperty<T>(string key, T value)
        {
            Properties[key] = value;
        }

        public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
        {
            _components.Add(middleware);
            return this;
        }

        public IApplicationBuilder New()
        {
            return new ApplicationBuilder(this);
        }

        public RequestDelegate Build()
        {
            RequestDelegate app = context =>
            {
                // If we reach the end of the pipeline, but we have an endpoint, then something unexpected has happened.
                // This could happen if user code sets an endpoint, but they forgot to add the UseEndpoint middleware.
                var endpoint = context.GetEndpoint();
                var endpointRequestDelegate = endpoint?.RequestDelegate;
                if (endpointRequestDelegate != null)
                {
                    var message =
                        $"The request reached the end of the pipeline without executing the endpoint: '{endpoint.DisplayName}'. " +
                        $"Please register the EndpointMiddleware using '{nameof(IApplicationBuilder)}.UseEndpoints(...)' if using " +
                        $"routing.";
                    throw new InvalidOperationException(message);
                }

                context.Response.StatusCode = 404;
                return Task.CompletedTask;
            };

            foreach (var component in _components.Reverse())
            {
                app = component(app);
            }

            return app;
        }
    }
}
复制代码

其中 RequestDelegate 委托的声明,如下:

复制代码
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Http
{
    /// <summary>
    /// A function that can process an HTTP request.
    /// </summary>
    /// <param name="context">The <see cref="HttpContext"/> for the request.</param>
    /// <returns>A task that represents the completion of request processing.</returns>
    public delegate Task RequestDelegate(HttpContext context);
}
复制代码

仔细阅读后可以发现其实 app.Use(...) 这个方法就只是将 Func<RequestDelegate, RequestDelegate> 类型的委托参数添加到 _components 这个集合中。

最终程序会调用 ApplicationBuilder 类的 Build() 方法去构建Http请求处理管道,接下来我们就重点来关注一下这个 Build() 方法,如下:

复制代码
public RequestDelegate Build()
{
    RequestDelegate app = context =>
    {
        // If we reach the end of the pipeline, but we have an endpoint, then something unexpected has happened.
        // This could happen if user code sets an endpoint, but they forgot to add the UseEndpoint middleware.
        var endpoint = context.GetEndpoint();
        var endpointRequestDelegate = endpoint?.RequestDelegate;
        if (endpointRequestDelegate != null)
        {
            var message =
                $"The request reached the end of the pipeline without executing the endpoint: '{endpoint.DisplayName}'. " +
                $"Please register the EndpointMiddleware using '{nameof(IApplicationBuilder)}.UseEndpoints(...)' if using " +
                $"routing.";
            throw new InvalidOperationException(message);
        }

        context.Response.StatusCode = 404;
        return Task.CompletedTask;
    };

    foreach (var component in _components.Reverse())
    {
        app = component(app);
    }

    return app;
}
复制代码

仔细观察上面的源码后我们可以发现: 

1、首先它是将 _components 这个集合反转(即:_components.Reverse()),然后依次调用里面的中间件(Func<RequestDelegate, RequestDelegate>委托),这也就解释了为什么网站启动时我们的控制台会依次输出 “middleware 3” 、“middleware 2”、“middleware 1” 的原因。 

2、调用反转后的第一个中间件(即:注册的最后一个中间件)时传入的参数是状态码为404的 RequestDelegate 委托,作为默认处理步骤。

3、在调用反转后的中间件时,它是用第一个中间件的返回值作为调用第二个中间件的参数,用第二个中间件的返回值作为调用第三个中间件的参数,依次类推。这也就是为什么说注册时的那个 next 参数是指向注册时下一个中间件的原因。 

4、Build() 方法最终返回的是调用反转后最后一个中间件(即:注册的第一个中间件)的返回值。

下面我们来看一下Use方法的另外一个重载,如下所示:

复制代码
//中间件4
//Use方法的另外一个重载
app.Use(async (context, next) =>
{
    await Task.Run(() => Console.WriteLine($"This is middleware 4 Start"));
    await next();
    await Task.Run(() => Console.WriteLine($"This is middleware 4 End"));
});
复制代码

我们找到它的源码,如下:

复制代码
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// Extension methods for adding middleware.
    /// </summary>
    public static class UseExtensions
    {
        /// <summary>
        /// Adds a middleware delegate defined in-line to the application's request pipeline.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param>
        /// <param name="middleware">A function that handles the request or calls the given next function.</param>
        /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns>
        public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware)
        {
            return app.Use(next =>
            {
                return context =>
                {
                    Func<Task> simpleNext = () => next(context);
                    return middleware(context, simpleNext);
                };
            });
        }
    }
}
复制代码

可以发现其实它是个扩展方法,主要就是对 app.Use(...) 这个方法包装了一下,最终调用的还是 app.Use(...) 这个方法。

最后我们来看一下 app.Run(...) 这个扩展方法,如下所示:

//app.Use(_ => handler);
app.Run(async context =>
{
    await Task.Run(() => Console.WriteLine($"This is Run"));
});

我们找到它的源码,如下:

复制代码
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// Extension methods for adding terminal middleware.
    /// </summary>
    public static class RunExtensions
    {
        /// <summary>
        /// Adds a terminal middleware delegate to the application's request pipeline.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param>
        /// <param name="handler">A delegate that handles the request.</param>
        public static void Run(this IApplicationBuilder app, RequestDelegate handler)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }

            app.Use(_ => handler);
        }
    }
}
复制代码

可以发现,其实 app.Run(...) 这个扩展方法最终也是调用 app.Use(...) 这个方法,只不过它直接丢弃了 next 参数,故调用这个方法会终止管道,它属于终端中间件。

更多关于ASP.NET Core 中间件的相关知识可参考微软官方文档: https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0

至此本文就全部介绍完了,如果觉得对您有所启发请记得点个赞哦!!!

 

Demo源码:

链接:https://pan.baidu.com/s/103ldhtjVcB3vJZidlcq0Yw 
提取码:7rt1

此文由博主精心撰写转载请保留此原文链接https://www.cnblogs.com/xyh9039/p/16146620.html

版权声明:如有雷同纯属巧合,如有侵权请及时联系本人修改,谢谢!!!

 

 出处:https://www.cnblogs.com/xyh9039/p/16146620.html

=======================================================================================

ASP.NET Core 中间件(Middleware)的使用及其源码解析(二)- 使用UseMiddleware扩展方法注册自定义中间件

有的中间件功能比较简单,有的则比较复杂,并且依赖其它组件。除了直接用 ApplicationBuilder 的 Use() 方法注册中间件外,还可以使用 ApplicationBuilder 的扩展方法 UseMiddleware() 注册自定义中间件。

废话不多说,我们在上一篇的基础上加一个自定义中间件类 CustomMiddleware ,如下所示:

复制代码
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NETCoreMiddleware.Middlewares
{
    /// <summary>
    /// 自定义中间件
    /// </summary>
    public class CustomMiddleware
    {
        /// <summary>
        /// 保存下一个中间件
        /// </summary>
        private readonly RequestDelegate _next;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="next">下一个中间件</param>
        public CustomMiddleware(RequestDelegate next)
        {
            Console.WriteLine($"{typeof(CustomMiddleware)} 被构造");
            _next = next;
        }

        /// <summary>
        /// 中间件方法
        /// </summary>
        public async Task InvokeAsync(HttpContext context)
        {
            await Task.Run(() => Console.WriteLine($"This is CustomMiddleware Start"));
            await _next.Invoke(context); //可通过不调用 next 参数使请求管道短路
            await Task.Run(() => Console.WriteLine($"This is CustomMiddleware End"));
        }
    }
}
复制代码

接着将该中间件装配到我们的Http请求处理管道中,如下所示(标红部分):

复制代码
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using NETCoreMiddleware.Middlewares;

namespace NETCoreMiddleware
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        //服务注册(往容器中添加服务)
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

        /// <summary>
        /// 配置Http请求处理管道
        /// Http请求管道模型---就是Http请求被处理的步骤
        /// 所谓管道,就是拿着HttpContext,经过多个步骤的加工,生成Response,这就是管道
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            #region 环境参数

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            #endregion 环境参数

            //静态文件中间件
            app.UseStaticFiles();

            #region Use中间件

            //中间件1
            app.Use(next =>
            {
                Console.WriteLine("middleware 1");
                return async context =>
                {
                    await Task.Run(() =>
                    {
                        Console.WriteLine("");
                        Console.WriteLine("===================================Middleware===================================");
                        Console.WriteLine($"This is middleware 1 Start");
                    });
                    await next.Invoke(context);
                    await Task.Run(() =>
                    {
                        Console.WriteLine($"This is middleware 1 End");
                        Console.WriteLine("===================================Middleware===================================");
                    });
                };
            });

            //中间件2
            app.Use(next =>
            {
                Console.WriteLine("middleware 2");
                return async context =>
                {
                    await Task.Run(() => Console.WriteLine($"This is middleware 2 Start"));
                    await next.Invoke(context); //可通过不调用 next 参数使请求管道短路
                    await Task.Run(() => Console.WriteLine($"This is middleware 2 End"));
                };
            });

            //中间件3
            app.Use(next =>
            {
                Console.WriteLine("middleware 3");
                return async context =>
                {
                    await Task.Run(() => Console.WriteLine($"This is middleware 3 Start"));
                    await next.Invoke(context);
                    await Task.Run(() => Console.WriteLine($"This is middleware 3 End"));
                };
            });

            //中间件4
            //Use方法的另外一个重载
            app.Use(async (context, next) =>
            {
                await Task.Run(() => Console.WriteLine($"This is middleware 4 Start"));
                await next();
                await Task.Run(() => Console.WriteLine($"This is middleware 4 End"));
            });

            #endregion Use中间件

            #region UseMiddleware中间件

            app.UseMiddleware<CustomMiddleware>();

            #endregion UseMiddleware中间件

            #region 终端中间件

            //app.Use(_ => handler);
            app.Run(async context =>
            {
                await Task.Run(() => Console.WriteLine($"This is Run"));
            });

            #endregion 终端中间件

            #region 最终把请求交给MVC

            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            #endregion 最终把请求交给MVC
        }
    }
}
复制代码

下面我们使用命令行(CLI)方式启动我们的网站,如下所示:

启动成功后,我们来访问一下 “/home/index” ,控制台输出结果如下所示:

可以发现我们自定义的中间件生效了。

 

下面我们结合ASP.NET Core源码来分析下其实现原理: 

我们将光标移动到 UseMiddleware 处按 F12 转到定义,如下所示:

可以发现它是位于 UseMiddlewareExtensions 扩展类中的,我们找到 UseMiddlewareExtensions 类的源码,如下所示:

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Abstractions;
using Microsoft.Extensions.Internal;

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// Extension methods for adding typed middleware.
    /// </summary>
    public static class UseMiddlewareExtensions
    {
        internal const string InvokeMethodName = "Invoke";
        internal const string InvokeAsyncMethodName = "InvokeAsync";

        private static readonly MethodInfo GetServiceInfo = typeof(UseMiddlewareExtensions).GetMethod(nameof(GetService), BindingFlags.NonPublic | BindingFlags.Static);

        /// <summary>
        /// Adds a middleware type to the application's request pipeline.
        /// </summary>
        /// <typeparam name="TMiddleware">The middleware type.</typeparam>
        /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param>
        /// <param name="args">The arguments to pass to the middleware type instance's constructor.</param>
        /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns>
        public static IApplicationBuilder UseMiddleware<TMiddleware>(this IApplicationBuilder app, params object[] args)
        {
            return app.UseMiddleware(typeof(TMiddleware), args);
        }

        /// <summary>
        /// Adds a middleware type to the application's request pipeline.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param>
        /// <param name="middleware">The middleware type.</param>
        /// <param name="args">The arguments to pass to the middleware type instance's constructor.</param>
        /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns>
        public static IApplicationBuilder UseMiddleware(this IApplicationBuilder app, Type middleware, params object[] args)
        {
            if (typeof(IMiddleware).GetTypeInfo().IsAssignableFrom(middleware.GetTypeInfo()))
            {
                // IMiddleware doesn't support passing args directly since it's
                // activated from the container
                if (args.Length > 0)
                {
                    throw new NotSupportedException(Resources.FormatException_UseMiddlewareExplicitArgumentsNotSupported(typeof(IMiddleware)));
                }

                return UseMiddlewareInterface(app, middleware);
            }

            var applicationServices = app.ApplicationServices;
            return app.Use(next =>
            {
                var methods = middleware.GetMethods(BindingFlags.Instance | BindingFlags.Public);
                var invokeMethods = methods.Where(m =>
                    string.Equals(m.Name, InvokeMethodName, StringComparison.Ordinal)
                    || string.Equals(m.Name, InvokeAsyncMethodName, StringComparison.Ordinal)
                    ).ToArray();

                if (invokeMethods.Length > 1)
                {
                    throw new InvalidOperationException(Resources.FormatException_UseMiddleMutlipleInvokes(InvokeMethodName, InvokeAsyncMethodName));
                }

                if (invokeMethods.Length == 0)
                {
                    throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoInvokeMethod(InvokeMethodName, InvokeAsyncMethodName, middleware));
                }

                var methodInfo = invokeMethods[0];
                if (!typeof(Task).IsAssignableFrom(methodInfo.ReturnType))
                {
                    throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNonTaskReturnType(InvokeMethodName, InvokeAsyncMethodName, nameof(Task)));
                }

                var parameters = methodInfo.GetParameters();
                if (parameters.Length == 0 || parameters[0].ParameterType != typeof(HttpContext))
                {
                    throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoParameters(InvokeMethodName, InvokeAsyncMethodName, nameof(HttpContext)));
                }

                var ctorArgs = new object[args.Length + 1];
                ctorArgs[0] = next;
                Array.Copy(args, 0, ctorArgs, 1, args.Length);
                var instance = ActivatorUtilities.CreateInstance(app.ApplicationServices, middleware, ctorArgs);
                if (parameters.Length == 1)
                {
                    return (RequestDelegate)methodInfo.CreateDelegate(typeof(RequestDelegate), instance);
                }

                var factory = Compile<object>(methodInfo, parameters);

                return context =>
                {
                    var serviceProvider = context.RequestServices ?? applicationServices;
                    if (serviceProvider == null)
                    {
                        throw new InvalidOperationException(Resources.FormatException_UseMiddlewareIServiceProviderNotAvailable(nameof(IServiceProvider)));
                    }

                    return factory(instance, context, serviceProvider);
                };
            });
        }

        private static IApplicationBuilder UseMiddlewareInterface(IApplicationBuilder app, Type middlewareType)
        {
            return app.Use(next =>
            {
                return async context =>
                {
                    var middlewareFactory = (IMiddlewareFactory)context.RequestServices.GetService(typeof(IMiddlewareFactory));
                    if (middlewareFactory == null)
                    {
                        // No middleware factory
                        throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoMiddlewareFactory(typeof(IMiddlewareFactory)));
                    }

                    var middleware = middlewareFactory.Create(middlewareType);
                    if (middleware == null)
                    {
                        // The factory returned null, it's a broken implementation
                        throw new InvalidOperationException(Resources.FormatException_UseMiddlewareUnableToCreateMiddleware(middlewareFactory.GetType(), middlewareType));
                    }

                    try
                    {
                        await middleware.InvokeAsync(context, next);
                    }
                    finally
                    {
                        middlewareFactory.Release(middleware);
                    }
                };
            });
        }

        private static Func<T, HttpContext, IServiceProvider, Task> Compile<T>(MethodInfo methodInfo, ParameterInfo[] parameters)
        {
            // If we call something like
            //
            // public class Middleware
            // {
            //    public Task Invoke(HttpContext context, ILoggerFactory loggerFactory)
            //    {
            //
            //    }
            // }
            //

            // We'll end up with something like this:
            //   Generic version:
            //
            //   Task Invoke(Middleware instance, HttpContext httpContext, IServiceProvider provider)
            //   {
            //      return instance.Invoke(httpContext, (ILoggerFactory)UseMiddlewareExtensions.GetService(provider, typeof(ILoggerFactory));
            //   }

            //   Non generic version:
            //
            //   Task Invoke(object instance, HttpContext httpContext, IServiceProvider provider)
            //   {
            //      return ((Middleware)instance).Invoke(httpContext, (ILoggerFactory)UseMiddlewareExtensions.GetService(provider, typeof(ILoggerFactory));
            //   }

            var middleware = typeof(T);

            var httpContextArg = Expression.Parameter(typeof(HttpContext), "httpContext");
            var providerArg = Expression.Parameter(typeof(IServiceProvider), "serviceProvider");
            var instanceArg = Expression.Parameter(middleware, "middleware");

            var methodArguments = new Expression[parameters.Length];
            methodArguments[0] = httpContextArg;
            for (int i = 1; i < parameters.Length; i++)
            {
                var parameterType = parameters[i].ParameterType;
                if (parameterType.IsByRef)
                {
                    throw new NotSupportedException(Resources.FormatException_InvokeDoesNotSupportRefOrOutParams(InvokeMethodName));
                }

                var parameterTypeExpression = new Expression[]
                {
                    providerArg,
                    Expression.Constant(parameterType, typeof(Type)),
                    Expression.Constant(methodInfo.DeclaringType, typeof(Type))
                };

                var getServiceCall = Expression.Call(GetServiceInfo, parameterTypeExpression);
                methodArguments[i] = Expression.Convert(getServiceCall, parameterType);
            }

            Expression middlewareInstanceArg = instanceArg;
            if (methodInfo.DeclaringType != typeof(T))
            {
                middlewareInstanceArg = Expression.Convert(middlewareInstanceArg, methodInfo.DeclaringType);
            }

            var body = Expression.Call(middlewareInstanceArg, methodInfo, methodArguments);

            var lambda = Expression.Lambda<Func<T, HttpContext, IServiceProvider, Task>>(body, instanceArg, httpContextArg, providerArg);

            return lambda.Compile();
        }

        private static object GetService(IServiceProvider sp, Type type, Type middleware)
        {
            var service = sp.GetService(type);
            if (service == null)
            {
                throw new InvalidOperationException(Resources.FormatException_InvokeMiddlewareNoService(type, middleware));
            }

            return service;
        }
    }
}
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions类源码

从中我们可以知道,它最终会调用下面的这个方法:

复制代码
/// <summary>
/// Adds a middleware type to the application's request pipeline.
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param>
/// <param name="middleware">The middleware type.</param>
/// <param name="args">The arguments to pass to the middleware type instance's constructor.</param>
/// <returns>The <see cref="IApplicationBuilder"/> instance.</returns>
public static IApplicationBuilder UseMiddleware(this IApplicationBuilder app, Type middleware, params object[] args)
{
    if (typeof(IMiddleware).GetTypeInfo().IsAssignableFrom(middleware.GetTypeInfo()))
    {
        // IMiddleware doesn't support passing args directly since it's
        // activated from the container
        if (args.Length > 0)
        {
            throw new NotSupportedException(Resources.FormatException_UseMiddlewareExplicitArgumentsNotSupported(typeof(IMiddleware)));
        }

        return UseMiddlewareInterface(app, middleware);
    }

    var applicationServices = app.ApplicationServices;
    return app.Use(next =>
    {
        var methods = middleware.GetMethods(BindingFlags.Instance | BindingFlags.Public);
        var invokeMethods = methods.Where(m =>
            string.Equals(m.Name, InvokeMethodName, StringComparison.Ordinal)
            || string.Equals(m.Name, InvokeAsyncMethodName, StringComparison.Ordinal)
            ).ToArray();

        if (invokeMethods.Length > 1)
        {
            throw new InvalidOperationException(Resources.FormatException_UseMiddleMutlipleInvokes(InvokeMethodName, InvokeAsyncMethodName));
        }

        if (invokeMethods.Length == 0)
        {
            throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoInvokeMethod(InvokeMethodName, InvokeAsyncMethodName, middleware));
        }

        var methodInfo = invokeMethods[0];
        if (!typeof(Task).IsAssignableFrom(methodInfo.ReturnType))
        {
            throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNonTaskReturnType(InvokeMethodName, InvokeAsyncMethodName, nameof(Task)));
        }

        var parameters = methodInfo.GetParameters();
        if (parameters.Length == 0 || parameters[0].ParameterType != typeof(HttpContext))
        {
            throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoParameters(InvokeMethodName, InvokeAsyncMethodName, nameof(HttpContext)));
        }

        var ctorArgs = new object[args.Length + 1];
        ctorArgs[0] = next;
        Array.Copy(args, 0, ctorArgs, 1, args.Length);
        var instance = ActivatorUtilities.CreateInstance(app.ApplicationServices, middleware, ctorArgs);
        if (parameters.Length == 1)
        {
            return (RequestDelegate)methodInfo.CreateDelegate(typeof(RequestDelegate), instance);
        }

        var factory = Compile<object>(methodInfo, parameters);

        return context =>
        {
            var serviceProvider = context.RequestServices ?? applicationServices;
            if (serviceProvider == null)
            {
                throw new InvalidOperationException(Resources.FormatException_UseMiddlewareIServiceProviderNotAvailable(nameof(IServiceProvider)));
            }

            return factory(instance, context, serviceProvider);
        };
    });
}
复制代码

其中 ActivatorUtilities 类的源码如下:

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.ExceptionServices;

#if ActivatorUtilities_In_DependencyInjection
using Microsoft.Extensions.Internal;

namespace Microsoft.Extensions.DependencyInjection
#else
namespace Microsoft.Extensions.Internal
#endif
{
    /// <summary>
    /// Helper code for the various activator services.
    /// </summary>

#if ActivatorUtilities_In_DependencyInjection
    public
#else
    // Do not take a dependency on this class unless you are explicitly trying to avoid taking a
    // dependency on Microsoft.AspNetCore.DependencyInjection.Abstractions.
    internal
#endif
    static class ActivatorUtilities
    {
        private static readonly MethodInfo GetServiceInfo =
            GetMethodInfo<Func<IServiceProvider, Type, Type, bool, object>>((sp, t, r, c) => GetService(sp, t, r, c));

        /// <summary>
        /// Instantiate a type with constructor arguments provided directly and/or from an <see cref="IServiceProvider"/>.
        /// </summary>
        /// <param name="provider">The service provider used to resolve dependencies</param>
        /// <param name="instanceType">The type to activate</param>
        /// <param name="parameters">Constructor arguments not provided by the <paramref name="provider"/>.</param>
        /// <returns>An activated object of type instanceType</returns>
        public static object CreateInstance(IServiceProvider provider, Type instanceType, params object[] parameters)
        {
            int bestLength = -1;
            var seenPreferred = false;

            ConstructorMatcher bestMatcher = default;

            if (!instanceType.GetTypeInfo().IsAbstract)
            {
                foreach (var constructor in instanceType
                    .GetTypeInfo()
                    .DeclaredConstructors)
                {
                    if (!constructor.IsStatic && constructor.IsPublic)
                    {
                        var matcher = new ConstructorMatcher(constructor);
                        var isPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false);
                        var length = matcher.Match(parameters);

                        if (isPreferred)
                        {
                            if (seenPreferred)
                            {
                                ThrowMultipleCtorsMarkedWithAttributeException();
                            }

                            if (length == -1)
                            {
                                ThrowMarkedCtorDoesNotTakeAllProvidedArguments();
                            }
                        }

                        if (isPreferred || bestLength < length)
                        {
                            bestLength = length;
                            bestMatcher = matcher;
                        }

                        seenPreferred |= isPreferred;
                    }
                }
            }

            if (bestLength == -1)
            {
                var message = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.";
                throw new InvalidOperationException(message);
            }

            return bestMatcher.CreateInstance(provider);
        }

        /// <summary>
        /// Create a delegate that will instantiate a type with constructor arguments provided directly
        /// and/or from an <see cref="IServiceProvider"/>.
        /// </summary>
        /// <param name="instanceType">The type to activate</param>
        /// <param name="argumentTypes">
        /// The types of objects, in order, that will be passed to the returned function as its second parameter
        /// </param>
        /// <returns>
        /// A factory that will instantiate instanceType using an <see cref="IServiceProvider"/>
        /// and an argument array containing objects matching the types defined in argumentTypes
        /// </returns>
        public static ObjectFactory CreateFactory(Type instanceType, Type[] argumentTypes)
        {
            FindApplicableConstructor(instanceType, argumentTypes, out ConstructorInfo constructor, out int?[] parameterMap);

            var provider = Expression.Parameter(typeof(IServiceProvider), "provider");
            var argumentArray = Expression.Parameter(typeof(object[]), "argumentArray");
            var factoryExpressionBody = BuildFactoryExpression(constructor, parameterMap, provider, argumentArray);

            var factoryLamda = Expression.Lambda<Func<IServiceProvider, object[], object>>(
                factoryExpressionBody, provider, argumentArray);

            var result = factoryLamda.Compile();
            return result.Invoke;
        }

        /// <summary>
        /// Instantiate a type with constructor arguments provided directly and/or from an <see cref="IServiceProvider"/>.
        /// </summary>
        /// <typeparam name="T">The type to activate</typeparam>
        /// <param name="provider">The service provider used to resolve dependencies</param>
        /// <param name="parameters">Constructor arguments not provided by the <paramref name="provider"/>.</param>
        /// <returns>An activated object of type T</returns>
        public static T CreateInstance<T>(IServiceProvider provider, params object[] parameters)
        {
            return (T)CreateInstance(provider, typeof(T), parameters);
        }


        /// <summary>
        /// Retrieve an instance of the given type from the service provider. If one is not found then instantiate it directly.
        /// </summary>
        /// <typeparam name="T">The type of the service</typeparam>
        /// <param name="provider">The service provider used to resolve dependencies</param>
        /// <returns>The resolved service or created instance</returns>
        public static T GetServiceOrCreateInstance<T>(IServiceProvider provider)
        {
            return (T)GetServiceOrCreateInstance(provider, typeof(T));
        }

        /// <summary>
        /// Retrieve an instance of the given type from the service provider. If one is not found then instantiate it directly.
        /// </summary>
        /// <param name="provider">The service provider</param>
        /// <param name="type">The type of the service</param>
        /// <returns>The resolved service or created instance</returns>
        public static object GetServiceOrCreateInstance(IServiceProvider provider, Type type)
        {
            return provider.GetService(type) ?? CreateInstance(provider, type);
        }

        private static MethodInfo GetMethodInfo<T>(Expression<T> expr)
        {
            var mc = (MethodCallExpression)expr.Body;
            return mc.Method;
        }

        private static object GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
        {
            var service = sp.GetService(type);
            if (service == null && !isDefaultParameterRequired)
            {
                var message = $"Unable to resolve service for type '{type}' while attempting to activate '{requiredBy}'.";
                throw new InvalidOperationException(message);
            }
            return service;
        }

        private static Expression BuildFactoryExpression(
            ConstructorInfo constructor,
            int?[] parameterMap,
            Expression serviceProvider,
            Expression factoryArgumentArray)
        {
            var constructorParameters = constructor.GetParameters();
            var constructorArguments = new Expression[constructorParameters.Length];

            for (var i = 0; i < constructorParameters.Length; i++)
            {
                var constructorParameter = constructorParameters[i];
                var parameterType = constructorParameter.ParameterType;
                var hasDefaultValue = ParameterDefaultValue.TryGetDefaultValue(constructorParameter, out var defaultValue);

                if (parameterMap[i] != null)
                {
                    constructorArguments[i] = Expression.ArrayAccess(factoryArgumentArray, Expression.Constant(parameterMap[i]));
                }
                else
                {
                    var parameterTypeExpression = new Expression[] { serviceProvider,
                        Expression.Constant(parameterType, typeof(Type)),
                        Expression.Constant(constructor.DeclaringType, typeof(Type)),
                        Expression.Constant(hasDefaultValue) };
                    constructorArguments[i] = Expression.Call(GetServiceInfo, parameterTypeExpression);
                }

                // Support optional constructor arguments by passing in the default value
                // when the argument would otherwise be null.
                if (hasDefaultValue)
                {
                    var defaultValueExpression = Expression.Constant(defaultValue);
                    constructorArguments[i] = Expression.Coalesce(constructorArguments[i], defaultValueExpression);
                }

                constructorArguments[i] = Expression.Convert(constructorArguments[i], parameterType);
            }

            return Expression.New(constructor, constructorArguments);
        }

        private static void FindApplicableConstructor(
            Type instanceType,
            Type[] argumentTypes,
            out ConstructorInfo matchingConstructor,
            out int?[] parameterMap)
        {
            matchingConstructor = null;
            parameterMap = null;

            if (!TryFindPreferredConstructor(instanceType, argumentTypes, ref matchingConstructor, ref parameterMap) &&
                !TryFindMatchingConstructor(instanceType, argumentTypes, ref matchingConstructor, ref parameterMap))
            {
                var message = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.";
                throw new InvalidOperationException(message);
            }
        }

        // Tries to find constructor based on provided argument types
        private static bool TryFindMatchingConstructor(
            Type instanceType,
            Type[] argumentTypes,
            ref ConstructorInfo matchingConstructor,
            ref int?[] parameterMap)
        {
            foreach (var constructor in instanceType.GetTypeInfo().DeclaredConstructors)
            {
                if (constructor.IsStatic || !constructor.IsPublic)
                {
                    continue;
                }

                if (TryCreateParameterMap(constructor.GetParameters(), argumentTypes, out int?[] tempParameterMap))
                {
                    if (matchingConstructor != null)
                    {
                        throw new InvalidOperationException($"Multiple constructors accepting all given argument types have been found in type '{instanceType}'. There should only be one applicable constructor.");
                    }

                    matchingConstructor = constructor;
                    parameterMap = tempParameterMap;
                }
            }

            return matchingConstructor != null;
        }

        // Tries to find constructor marked with ActivatorUtilitiesConstructorAttribute
        private static bool TryFindPreferredConstructor(
            Type instanceType,
            Type[] argumentTypes,
            ref ConstructorInfo matchingConstructor,
            ref int?[] parameterMap)
        {
            var seenPreferred = false;
            foreach (var constructor in instanceType.GetTypeInfo().DeclaredConstructors)
            {
                if (constructor.IsStatic || !constructor.IsPublic)
                {
                    continue;
                }

                if (constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false))
                {
                    if (seenPreferred)
                    {
                        ThrowMultipleCtorsMarkedWithAttributeException();
                    }

                    if (!TryCreateParameterMap(constructor.GetParameters(), argumentTypes, out int?[] tempParameterMap))
                    {
                        ThrowMarkedCtorDoesNotTakeAllProvidedArguments();
                    }

                    matchingConstructor = constructor;
                    parameterMap = tempParameterMap;
                    seenPreferred = true;
                }
            }

            return matchingConstructor != null;
        }

        // Creates an injective parameterMap from givenParameterTypes to assignable constructorParameters.
        // Returns true if each given parameter type is assignable to a unique; otherwise, false.
        private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters, Type[] argumentTypes, out int?[] parameterMap)
        {
            parameterMap = new int?[constructorParameters.Length];

            for (var i = 0; i < argumentTypes.Length; i++)
            {
                var foundMatch = false;
                var givenParameter = argumentTypes[i].GetTypeInfo();

                for (var j = 0; j < constructorParameters.Length; j++)
                {
                    if (parameterMap[j] != null)
                    {
                        // This ctor parameter has already been matched
                        continue;
                    }

                    if (constructorParameters[j].ParameterType.GetTypeInfo().IsAssignableFrom(givenParameter))
                    {
                        foundMatch = true;
                        parameterMap[j] = i;
                        break;
                    }
                }

                if (!foundMatch)
                {
                    return false;
                }
            }

            return true;
        }

        private struct ConstructorMatcher
        {
            private readonly ConstructorInfo _constructor;
            private readonly ParameterInfo[] _parameters;
            private readonly object[] _parameterValues;

            public ConstructorMatcher(ConstructorInfo constructor)
            {
                _constructor = constructor;
                _parameters = _constructor.GetParameters();
                _parameterValues = new object[_parameters.Length];
            }

            public int Match(object[] givenParameters)
            {
                var applyIndexStart = 0;
                var applyExactLength = 0;
                for (var givenIndex = 0; givenIndex != givenParameters.Length; givenIndex++)
                {
                    var givenType = givenParameters[givenIndex]?.GetType().GetTypeInfo();
                    var givenMatched = false;

                    for (var applyIndex = applyIndexStart; givenMatched == false && applyIndex != _parameters.Length; ++applyIndex)
                    {
                        if (_parameterValues[applyIndex] == null &&
                            _parameters[applyIndex].ParameterType.GetTypeInfo().IsAssignableFrom(givenType))
                        {
                            givenMatched = true;
                            _parameterValues[applyIndex] = givenParameters[givenIndex];
                            if (applyIndexStart == applyIndex)
                            {
                                applyIndexStart++;
                                if (applyIndex == givenIndex)
                                {
                                    applyExactLength = applyIndex;
                                }
                            }
                        }
                    }

                    if (givenMatched == false)
                    {
                        return -1;
                    }
                }
                return applyExactLength;
            }

            public object CreateInstance(IServiceProvider provider)
            {
                for (var index = 0; index != _parameters.Length; index++)
                {
                    if (_parameterValues[index] == null)
                    {
                        var value = provider.GetService(_parameters[index].ParameterType);
                        if (value == null)
                        {
                            if (!ParameterDefaultValue.TryGetDefaultValue(_parameters[index], out var defaultValue))
                            {
                                throw new InvalidOperationException($"Unable to resolve service for type '{_parameters[index].ParameterType}' while attempting to activate '{_constructor.DeclaringType}'.");
                            }
                            else
                            {
                                _parameterValues[index] = defaultValue;
                            }
                        }
                        else
                        {
                            _parameterValues[index] = value;
                        }
                    }
                }

#if NETCOREAPP
                return _constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
#else
                try
                {
                    return _constructor.Invoke(_parameterValues);
                }
                catch (TargetInvocationException ex) when (ex.InnerException != null)
                {
                    ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
                    // The above line will always throw, but the compiler requires we throw explicitly.
                    throw;
                }
#endif
            }
        }

        private static void ThrowMultipleCtorsMarkedWithAttributeException()
        {
            throw new InvalidOperationException($"Multiple constructors were marked with {nameof(ActivatorUtilitiesConstructorAttribute)}.");
        }

        private static void ThrowMarkedCtorDoesNotTakeAllProvidedArguments()
        {
            throw new InvalidOperationException($"Constructor marked with {nameof(ActivatorUtilitiesConstructorAttribute)} does not accept all given argument types.");
        }
    }
}
Microsoft.Extensions.Internal.ActivatorUtilities类源码

仔细阅读上面的源码后我们会发现:如果 Invoke(或InvokeAsync)方法只有一个参数(HttpContext)则它会把 Invoke(或InvokeAsync)方法包装为 RequestDelegate ,进而包装为 Func<RequestDelegate, RequestDelegate> ,最后再调用 app.Use(...) 这个方法进行注册;如果 Invoke(或InvokeAsync)方法有多个参数,不符合 RequestDelegate 委托的签名,则它会对 Invoke(或InvokeAsync)方法进行二次包装以符合 RequestDelegate 委托的签名;在二次包装过程中框架会尝试从依赖注入容器中获取 Invoke(或InvokeAsync)方法所需的参数。

此外我们可以得出一些结论,如下:

关于自定义中间件的方法:

1、中间件的方法名必须叫 Invoke 或者 InvokeAsync ,且为 public ,非 static 。

2、Invoke 或者 InvokeAsync 方法第一个参数必须是 HttpContext 类型。

3、Invoke 或者 InvokeAsync 方法的返回值类型必须是 Task 。

4、Invoke 或者 InvokeAsync 方法可以有多个参数,除 HttpContext 外其它参数会尝试从依赖注入容器中获取。

5、Invoke 或者 InvokeAsync 方法不能有重载。

 

关于自定义中间件的构造函数:

1、构造函数必须包含 RequestDelegate 参数,该参数传入的是下一个中间件。

2、构造函数参数中的 RequestDelegate 参数不是必须放在第一个,可以是任意位置。

3、构造函数可以有多个参数,参数会优先从给定的参数列表中查找,其次会从依赖注入容器中获取,获取失败会尝试获取默认值,都失败则会抛出异常。

4、构造函数可以有多个,届时会根据构造函数参数列表和给定的参数列表选择匹配度最高的一个。

 

个人建议:

1、除极特殊情况外只保留一个构造函数,以省去多余的构造函数匹配检查。

2、在构造函数中注入所需依赖而不是在 Invoke 或者 InvokeAsync 方法中注入。

3、关于构造函数参数的顺序,把 RequestDelegate 放在第一个;之后是 UseMiddleware 方法中给出的参数,而且构造函数中参数顺序和给定参数列表中的顺序最好也相同;然后是需要注入的参数;最后是有默认值的参数。以上除了默认值参数必须放在最后外其余的顺序都不是必须的,但按照上面的顺序会比较清晰,而且能使实例创建的开销最小。

4、Invoke 或者 InvokeAsync 方法只保留一个 HttpContext 参数,这样可以省去对 Invoke 或者 InvokeAsync 方法的二次包装。

 

本文部分内容参考博文:https://www.cnblogs.com/durow/p/5748124.html

更多关于ASP.NET Core 中间件的相关知识可参考微软官方文档: https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0

至此本文就全部介绍完了,如果觉得对您有所启发请记得点个赞哦!!!

 

Demo源码:

链接:https://pan.baidu.com/s/11NLDtt_cKPFxDbA3fW8Btg 
提取码:0hyo

此文由博主精心撰写转载请保留此原文链接:https://www.cnblogs.com/xyh9039/p/16414344.html

版权声明:如有雷同纯属巧合,如有侵权请及时联系本人修改,谢谢!!! 

 

出处:https://www.cnblogs.com/xyh9039/p/16414344.html

=======================================================================================

ASP.NET Core 中间件(Middleware)的使用及其源码解析(三)- 对中间件管道进行分支

如果业务逻辑比较简单的话,一条主管道就够了,确实用不到分支管道。不过当业务逻辑比较复杂的时候,有时候我们可能希望根据情况的不同使用特殊的一组中间件来处理 HttpContext。这种情况下如果只用一条管道,处理起来会非常麻烦和混乱。此时就可以使用 Map/MapWhen/UseWhen 建立一个分支管道,当条件符合我们的设定时,由这个分支管道来处理 HttpContext。使用 Map/MapWhen/UseWhen 添加分支管道是很容易的,只要提供合适跳转到分支管道的判断逻辑,以及分支管道的构建方法就可以了。

一、对中间件管道进行分支

废话不多说,我们直接通过一个Demo来看一下如何对中间件管道进行分支,如下:

复制代码
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using NETCoreMiddleware.Middlewares;

namespace NETCoreMiddleware
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        //服务注册(往容器中添加服务)
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

        /// <summary>
        /// 配置Http请求处理管道
        /// Http请求管道模型---就是Http请求被处理的步骤
        /// 所谓管道,就是拿着HttpContext,经过多个步骤的加工,生成Response,这就是管道
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            #region 环境参数

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            #endregion 环境参数

            //静态文件中间件
            app.UseStaticFiles();

            #region 创建管道分支

            //Map管道分支
            app.Map("/map1", HandleMapTest1);
            app.Map("/map2", HandleMapTest2);

            //MapWhen管道分支
            app.MapWhen(context => context.Request.Query.ContainsKey("mapwhen"), HandleBranch);

            //UseWhen管道分支
            //UseWhen 与 MapWhen 不同的是,如果这个分支不发生短路或包含终端中间件,则会重新加入主管道
            app.UseWhen(context => context.Request.Query.ContainsKey("usewhen"), HandleBranchAndRejoin);

            #endregion 创建管道分支

            #region Use中间件

            //中间件1
            app.Use(next =>
            {
                Console.WriteLine("middleware 1");
                return async context =>
                {
                    await Task.Run(() =>
                    {
                        Console.WriteLine("");
                        Console.WriteLine("===================================Middleware===================================");
                        Console.WriteLine($"This is middleware 1 Start");
                    });
                    await next.Invoke(context);
                    await Task.Run(() =>
                    {
                        Console.WriteLine($"This is middleware 1 End");
                        Console.WriteLine("===================================Middleware===================================");
                    });
                };
            });

            //中间件2
            app.Use(next =>
            {
                Console.WriteLine("middleware 2");
                return async context =>
                {
                    await Task.Run(() => Console.WriteLine($"This is middleware 2 Start"));
                    await next.Invoke(context); //可通过不调用 next 参数使请求管道短路
                    await Task.Run(() => Console.WriteLine($"This is middleware 2 End"));
                };
            });

            //中间件3
            app.Use(next =>
            {
                Console.WriteLine("middleware 3");
                return async context =>
                {
                    await Task.Run(() => Console.WriteLine($"This is middleware 3 Start"));
                    await next.Invoke(context);
                    await Task.Run(() => Console.WriteLine($"This is middleware 3 End"));
                };
            });

            //中间件4
            //Use方法的另外一个重载
            app.Use(async (context, next) =>
            {
                await Task.Run(() => Console.WriteLine($"This is middleware 4 Start"));
                await next();
                await Task.Run(() => Console.WriteLine($"This is middleware 4 End"));
            });

            #endregion Use中间件

            #region UseMiddleware中间件

            app.UseMiddleware<CustomMiddleware>();

            #endregion UseMiddleware中间件

            #region 终端中间件

            //app.Use(_ => handler);
            app.Run(async context =>
            {
                await Task.Run(() => Console.WriteLine($"This is Run"));
            });

            #endregion 终端中间件

            #region 最终把请求交给MVC

            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            #endregion 最终把请求交给MVC
        }

        #region 创建管道分支

        /// <summary>
        /// Map管道分支1
        /// </summary>
        /// <param name="app"></param>
        static void HandleMapTest1(IApplicationBuilder app)
        {
            //中间件
            app.Use(next =>
            {
                Console.WriteLine("HandleMapTest1");
                return async context =>
                {
                    await Task.Run(() =>
                    {
                        Console.WriteLine("");
                        Console.WriteLine($"This is HandleMapTest1 Start");
                    });
                    await next.Invoke(context); //可通过不调用 next 参数使请求管道短路
                    await Task.Run(() => Console.WriteLine($"This is HandleMapTest1 End"));
                };
            });
        }

        /// <summary>
        /// Map管道分支2
        /// </summary>
        /// <param name="app"></param>
        static void HandleMapTest2(IApplicationBuilder app)
        {
            //中间件
            app.Use(next =>
            {
                Console.WriteLine("HandleMapTest2");
                return async context =>
                {
                    await Task.Run(() =>
                    {
                        Console.WriteLine("");
                        Console.WriteLine($"This is HandleMapTest2 Start");
                    });
                    await next.Invoke(context); //可通过不调用 next 参数使请求管道短路
                    await Task.Run(() => Console.WriteLine($"This is HandleMapTest2 End"));
                };
            });
        }

        /// <summary>
        /// MapWhen管道分支
        /// </summary>
        /// <param name="app"></param>
        static void HandleBranch(IApplicationBuilder app)
        {
            //中间件
            app.Use(next =>
            {
                Console.WriteLine("HandleBranch");
                return async context =>
                {
                    await Task.Run(() =>
                    {
                        Console.WriteLine("");
                        Console.WriteLine($"This is HandleBranch Start");
                    });
                    await next.Invoke(context); //可通过不调用 next 参数使请求管道短路
                    await Task.Run(() => Console.WriteLine($"This is HandleBranch End"));
                };
            });
        }

        /// <summary>
        /// UseWhen管道分支
        /// </summary>
        /// <param name="app"></param>
        static void HandleBranchAndRejoin(IApplicationBuilder app)
        {
            //中间件
            app.Use(next =>
            {
                Console.WriteLine("HandleBranchAndRejoin");
                return async context =>
                {
                    await Task.Run(() =>
                    {
                        Console.WriteLine("");
                        Console.WriteLine($"This is HandleBranchAndRejoin Start");
                    });
                    await next.Invoke(context); //可通过不调用 next 参数使请求管道短路
                    await Task.Run(() => Console.WriteLine($"This is HandleBranchAndRejoin End"));
                };
            });
        }

        #endregion 创建管道分支
    }
}
复制代码

下面我们使用命令行(CLI)方式启动我们的网站,如下所示:

启动成功后,我们来访问一下 “http://localhost:5000/map1/” ,控制台输出结果如下所示:

访问 “http://localhost:5000/map2/” ,控制台输出结果如下所示:

访问 “http://localhost:5000/home/?mapwhen=1” ,控制台输出结果如下所示:

访问 “http://localhost:5000/home/?usewhen=1” ,控制台输出结果如下所示: 

Map 扩展用作约定来创建管道分支。 Map 基于给定请求路径的匹配项来创建请求管道分支。 如果请求路径以给定路径开头,则执行分支。

MapWhen 基于给定谓词的结果创建请求管道分支。 Func<HttpContext, bool> 类型的任何谓词均可用于将请求映射到管道的新分支。 

UseWhen 也基于给定谓词的结果创建请求管道分支。 与 MapWhen 不同的是,如果这个分支不发生短路或包含终端中间件,则会重新加入主管道。

二、中间件管道分支源码解析

下面我们结合ASP.NET Core源码来分析下其实现原理: 

1、Map扩展原理

我们将光标移动到 Map 处按 F12 转到定义,如下所示:

可以发现它是位于 MapExtensions 扩展类中的,我们找到 MapExtensions 类的源码,如下所示:

复制代码
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Builder.Extensions;

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// Extension methods for the <see cref="MapMiddleware"/>.
    /// </summary>
    public static class MapExtensions
    {
        /// <summary>
        /// Branches the request pipeline based on matches of the given request path. If the request path starts with
        /// the given path, the branch is executed.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param>
        /// <param name="pathMatch">The request path to match.</param>
        /// <param name="configuration">The branch to take for positive path matches.</param>
        /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns>
        public static IApplicationBuilder Map(this IApplicationBuilder app, PathString pathMatch, Action<IApplicationBuilder> configuration)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if (pathMatch.HasValue && pathMatch.Value.EndsWith("/", StringComparison.Ordinal))
            {
                throw new ArgumentException("The path must not end with a '/'", nameof(pathMatch));
            }

            // create branch
            var branchBuilder = app.New();
            configuration(branchBuilder);
            var branch = branchBuilder.Build();

            var options = new MapOptions
            {
                Branch = branch,
                PathMatch = pathMatch,
            };
            return app.Use(next => new MapMiddleware(next, options).Invoke);
        }
    }
}
复制代码

其中 ApplicationBuilder 类的源码,如下所示: 

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Internal;

namespace Microsoft.AspNetCore.Builder
{
    public class ApplicationBuilder : IApplicationBuilder
    {
        private const string ServerFeaturesKey = "server.Features";
        private const string ApplicationServicesKey = "application.Services";

        private readonly IList<Func<RequestDelegate, RequestDelegate>> _components = new List<Func<RequestDelegate, RequestDelegate>>();

        public ApplicationBuilder(IServiceProvider serviceProvider)
        {
            Properties = new Dictionary<string, object>(StringComparer.Ordinal);
            ApplicationServices = serviceProvider;
        }

        public ApplicationBuilder(IServiceProvider serviceProvider, object server)
            : this(serviceProvider)
        {
            SetProperty(ServerFeaturesKey, server);
        }

        private ApplicationBuilder(ApplicationBuilder builder)
        {
            Properties = new CopyOnWriteDictionary<string, object>(builder.Properties, StringComparer.Ordinal);
        }

        public IServiceProvider ApplicationServices
        {
            get
            {
                return GetProperty<IServiceProvider>(ApplicationServicesKey);
            }
            set
            {
                SetProperty<IServiceProvider>(ApplicationServicesKey, value);
            }
        }

        public IFeatureCollection ServerFeatures
        {
            get
            {
                return GetProperty<IFeatureCollection>(ServerFeaturesKey);
            }
        }

        public IDictionary<string, object> Properties { get; }

        private T GetProperty<T>(string key)
        {
            object value;
            return Properties.TryGetValue(key, out value) ? (T)value : default(T);
        }

        private void SetProperty<T>(string key, T value)
        {
            Properties[key] = value;
        }

        public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
        {
            _components.Add(middleware);
            return this;
        }

        public IApplicationBuilder New()
        {
            return new ApplicationBuilder(this);
        }

        public RequestDelegate Build()
        {
            RequestDelegate app = context =>
            {
                // If we reach the end of the pipeline, but we have an endpoint, then something unexpected has happened.
                // This could happen if user code sets an endpoint, but they forgot to add the UseEndpoint middleware.
                var endpoint = context.GetEndpoint();
                var endpointRequestDelegate = endpoint?.RequestDelegate;
                if (endpointRequestDelegate != null)
                {
                    var message =
                        $"The request reached the end of the pipeline without executing the endpoint: '{endpoint.DisplayName}'. " +
                        $"Please register the EndpointMiddleware using '{nameof(IApplicationBuilder)}.UseEndpoints(...)' if using " +
                        $"routing.";
                    throw new InvalidOperationException(message);
                }

                context.Response.StatusCode = 404;
                return Task.CompletedTask;
            };

            foreach (var component in _components.Reverse())
            {
                app = component(app);
            }

            return app;
        }
    }
}
Microsoft.AspNetCore.Builder.ApplicationBuilder类源码

其中 MapMiddleware 类的源码,如下所示: 

复制代码
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Builder.Extensions
{
    /// <summary>
    /// Represents a middleware that maps a request path to a sub-request pipeline.
    /// </summary>
    public class MapMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly MapOptions _options;

        /// <summary>
        /// Creates a new instance of <see cref="MapMiddleware"/>.
        /// </summary>
        /// <param name="next">The delegate representing the next middleware in the request pipeline.</param>
        /// <param name="options">The middleware options.</param>
        public MapMiddleware(RequestDelegate next, MapOptions options)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _next = next;
            _options = options;
        }

        /// <summary>
        /// Executes the middleware.
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
        /// <returns>A task that represents the execution of this middleware.</returns>
        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            PathString matchedPath;
            PathString remainingPath;

            if (context.Request.Path.StartsWithSegments(_options.PathMatch, out matchedPath, out remainingPath))
            {
                // Update the path
                var path = context.Request.Path;
                var pathBase = context.Request.PathBase;
                context.Request.PathBase = pathBase.Add(matchedPath);
                context.Request.Path = remainingPath;

                try
                {
                    await _options.Branch(context);
                }
                finally
                {
                    context.Request.PathBase = pathBase;
                    context.Request.Path = path;
                }
            }
            else
            {
                await _next(context);
            }
        }
    }
}
复制代码

在前两篇文章中我们已经介绍过,中间件的注册和管道的构建都是通过 ApplicationBuilder 进行的。因此要构建一个分支管道,需要一个新的 ApplicationBuilder ,并用它来注册中间件,构建管道。为了在分支管道中也能够共享我们在当前 ApplicationBuilder 中注册的服务(或者说共享依赖注入容器,当然共享的并不止这些),在创建新的 ApplicationBuilder 时并不是直接 new 一个全新的,而是调用当前 ApplicationBuilder 的 New 方法在当前的基础上创建新的,共享了当前 ApplicationBuilder 的 Properties(其中包含了依赖注入容器)。 

在使用 Map 注册中间件时我们会传入一个 Action<IApplicationBuilder> 参数,它的作用就是当我们创建了新的 ApplicationBuilder 后,使用这个方法对其进行各种设置,最重要的就是在新的 ApplicationBuilder 上注册分支管道的中间件。配置完成后调用分支 ApplicationBuilder 的 Build 方法构建管道,并把第一个中间件保存下来作为分支管道的入口。

在使用 Map 注册中间件时传入了一个 PathString 参数,PathString 对象我们可以简单地认为是 string 。它用于记录 HttpContext.HttpRequest.Path 中要匹配的区段(Segment)。这个字符串参数结尾不能是“/”。如果匹配成功则进入分支管道,匹配失则败继续当前管道。

新构建的管道和用于匹配的字符串保存为 MapOptions 对象,保存了 Map 规则和分支管道的入口。之后构建 MapMiddleware 对象,并把它的 Invoke 方法包装为 RequestDelegate ,使用当前 ApplicationBuilder 的 Use 方法注册中间件。

2、MapWhen扩展原理

我们将光标移动到 MapWhen 处按 F12 转到定义,如下所示:

可以发现它是位于 MapWhenExtensions 扩展类中的,我们找到 MapWhenExtensions 类的源码,如下所示: 

复制代码
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Builder.Extensions;


namespace Microsoft.AspNetCore.Builder
{
    using Predicate = Func<HttpContext, bool>;

    /// <summary>
    /// Extension methods for the <see cref="MapWhenMiddleware"/>.
    /// </summary>
    public static class MapWhenExtensions
    {
        /// <summary>
        /// Branches the request pipeline based on the result of the given predicate.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="predicate">Invoked with the request environment to determine if the branch should be taken</param>
        /// <param name="configuration">Configures a branch to take</param>
        /// <returns></returns>
        public static IApplicationBuilder MapWhen(this IApplicationBuilder app, Predicate predicate, Action<IApplicationBuilder> configuration)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (predicate == null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            // create branch
            var branchBuilder = app.New();
            configuration(branchBuilder);
            var branch = branchBuilder.Build();

            // put middleware in pipeline
            var options = new MapWhenOptions
            {
                Predicate = predicate,
                Branch = branch,
            };
            return app.Use(next => new MapWhenMiddleware(next, options).Invoke);
        }
    }
}
复制代码

其中 MapWhenMiddleware 类的源码,如下所示: 

复制代码
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Builder.Extensions
{
    /// <summary>
    /// Represents a middleware that runs a sub-request pipeline when a given predicate is matched.
    /// </summary>
    public class MapWhenMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly MapWhenOptions _options;

        /// <summary>
        /// Creates a new instance of <see cref="MapWhenMiddleware"/>.
        /// </summary>
        /// <param name="next">The delegate representing the next middleware in the request pipeline.</param>
        /// <param name="options">The middleware options.</param>
        public MapWhenMiddleware(RequestDelegate next, MapWhenOptions options)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _next = next;
            _options = options;
        }

        /// <summary>
        /// Executes the middleware.
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
        /// <returns>A task that represents the execution of this middleware.</returns>
        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (_options.Predicate(context))
            {
                await _options.Branch(context);
            }
            else
            {
                await _next(context);
            }
        }
    }
}
复制代码

Map 主要通过 URL 中的 Path 来判断是否需要进入分支管道,但有时候我们很可能会有别的需求,例如我想对所有 Method 为 DELETE 的请求用特殊管道处理,这时候就需要用 MapWhen 了。MapWhen 是一种通用的 Map,可以由使用者来决定什么时候进入分支管道什么时候不进入。可以说 Map 是 MapWhen 的一种情况,因为这种情况太常见了,所以官方实现了一个。这样看来 MapWhen 就很简单了,在 Map 中我们传入参数 PathString 来进行 HttpRequest.Path 的匹配,而在 MapWhen 中我们传入 Func<HttpContext, bool> 参数,由我们自行指定,当返回 true 时进入分支管道,返回 false 则继续当前管道。

3、UseWhen扩展原理

我们将光标移动到 UseWhen 处按 F12 转到定义,如下所示: 

可以发现它是位于 UseWhenExtensions 扩展类中的,我们找到 UseWhenExtensions 类的源码,如下所示: 

复制代码
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Builder
{
    using Predicate = Func<HttpContext, bool>;

    /// <summary>
    /// Extension methods for <see cref="IApplicationBuilder"/>.
    /// </summary>
    public static class UseWhenExtensions
    {
        /// <summary>
        /// Conditionally creates a branch in the request pipeline that is rejoined to the main pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="predicate">Invoked with the request environment to determine if the branch should be taken</param>
        /// <param name="configuration">Configures a branch to take</param>
        /// <returns></returns>
        public static IApplicationBuilder UseWhen(this IApplicationBuilder app, Predicate predicate, Action<IApplicationBuilder> configuration)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (predicate == null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            // Create and configure the branch builder right away; otherwise,
            // we would end up running our branch after all the components
            // that were subsequently added to the main builder.
            var branchBuilder = app.New();
            configuration(branchBuilder);

            return app.Use(main =>
            {
                // This is called only when the main application builder 
                // is built, not per request.
                branchBuilder.Run(main);
                var branch = branchBuilder.Build();

                return context =>
                {
                    if (predicate(context))
                    {
                        return branch(context);
                    }
                    else
                    {
                        return main(context);
                    }
                };
            });
        }
    }
}
复制代码

UseWhen 也基于给定谓词的结果创建请求管道分支。 与 MapWhen 不同的是,如果这个分支不发生短路或包含终端中间件,则会重新加入主管道。

仔细阅读上面的源码后我们会发现,其实 Map/MapWhen/UseWhen 均为 app.Use(...) 的封装,主要是为了熟悉的人方便而已。

 

本文部分内容参考博文:https://www.cnblogs.com/durow/p/5752055.html

更多关于ASP.NET Core 中间件的相关知识可参考微软官方文档: https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0

至此本文就全部介绍完了,如果觉得对您有所启发请记得点个赞哦!!!

 

Demo源码:

链接:https://pan.baidu.com/s/18I66dBmKZUpfPCNn85HI2g 
提取码:2xcj

此文由博主精心撰写转载请保留此原文链接:https://www.cnblogs.com/xyh9039/p/16492284.html

版权声明:如有雷同纯属巧合,如有侵权请及时联系本人修改,谢谢!!!

 

出处:https://www.cnblogs.com/xyh9039/p/16492284.html

=======================================================================================