Asp.Net Core中间件

Asp.Net Core中间件

1、按照约定来穿件

2、具有类型为RequestDelegate的参数的公共构造函数

3、名为Invoke或者InvokeAsync的公共方法,这个方法必须满足两个条件:返回Task;接受类型HttpContext的第一个参数

public class FirstMiddleware
    {
        private readonly RequestDelegate _next;
        public FirstMiddleware(RequestDelegate next)
        {
            _next = next;
        }
​
        /// <summary>
        ///  中间件的功能代码就写在这里的
        /// </summary>
        public async Task InvokeAsync(HttpContext httpContext)
        {
           
        }
​
        /// <summary>
        ///  需要依赖其他类就把其他类加入进去,支持方法注入
        ///  依赖:IConfiguration
        /// </summary>
        public async Task InvokeAsync(HttpContext httpContext,IConfiguration configuration)
        {
​
        }
​
    }

中间件的功能代码

 public async Task InvokeAsync(HttpContext httpContext)
  {
      await httpContext.Response.WriteAsync($"输出请求路径 {httpContext.Request.Path}");
      //可以选择是否调用Next()
      //如果不调用,那么这个中间件会触发短路
      await _next(httpContext);
 }

简单调用

Startup.cs 类中 添加app.UseMiddleware(); 即可

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {​
      app.UseMiddleware<FirstMiddleware>();
  }

中间件扩展

  public static class CustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseTest(this IApplicationBuilder app)
        {
            return app.UseMiddleware<FirstMiddleware>();
        }
    }

startup.cs 中使用

  //app.UseMiddleware<FirstMiddleware>();
   app.UseTest();
原文地址:https://www.cnblogs.com/youmingkuang/p/14748318.html