在 ASP.NET Core 应用程序中添加自定义中间件
在这里,您将学习如何创建自己的自定义中间件并将其添加到 ASP.NET Core 应用程序的请求管道中。
自定义中间件组件与使用 Invoke() 方法的任何其他 .NET 类类似。然而,为了按顺序执行下一个中间件,它应该在构造函数中具有 RequestDelegate 类型参数。
Visual Studio 包括用于创建标准中间件类的模板。为此,右键单击要创建中间件类的项目或文件夹,然后选择 添加->添加新项。这将打开添加新项弹出窗口,然后选择中间件,如下所示。

然后并为其命名,然后单击添加按钮。这将为带有扩展方法的中间件添加一个新类,如下所示。
// 您可能需要在项目中安装 Microsoft.AspNetCore.Http.Abstractions 包public class MyMiddleware{private readonly RequestDelegate _next;public MyMiddleware(RequestDelegate next){_next = next;}public Task Invoke(HttpContext httpContext){return _next(httpContext);}}// 用于将中间件添加到 HTTP 请求管道的扩展方法。public static class MyMiddlewareExtensions{public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder){return builder.UseMiddleware<MyMiddleware>();}}
如上所述,Invoke() 方法不是异步的。因此,将其更改为异步,并在调用 next() 之前编写自定义逻辑;
public class MyMiddleware{private readonly RequestDelegate _next;private readonly ILogger _logger;public MyMiddleware(RequestDelegate next, ILoggerFactory logFactory){_next = next;_logger = logFactory.CreateLogger("MyMiddleware");}public async Task Invoke(HttpContext httpContext){_logger.LogInformation("MyMiddleware executing..");await _next(httpContext); // calling next middleware}}// 用于将中间件添加到 HTTP 请求管道的扩展方法。public static class MyMiddlewareExtensions{public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder){return builder.UseMiddleware<MyMiddleware>();}}
添加自定义中间件
现在,我们需要使用如下所示的 Use 扩展方法在请求管道中添加自定义中间件。
public void Configure(IApplicationBuilder app, IHostingEnvironment env){app.UseMyMiddleware();app.Run(async (context) =>{await context.Response.WriteAsync("Hello World!");});}
我们可以使用应用程序添加中间件。还可以使用 IApplicationBuilder 的 Middleware<MyMiddleware>() 方法。
因此,我们可以在 ASP.NET Core 应用程序中添加中间件了。