1、编写中间件

①方式一(中间件写在Startup.cs中)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  app.Use(async (context, next) =>
  {
    // TO DO
    await next();
  });
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
②方式二(中间件写在独立文件中)

  中间件写法:

public class TestMiddleware
    {
        private readonly RequestDelegate _next;

        public TestMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext httpContext)
        {
            // TO DO
            return _next(httpContext);
        }
    }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

  注册到IApplicationBuilder:

public static class TestMiddlewareExtensions
    {
        public static IApplicationBuilder UseTestMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<TestMiddleware>();
        }
    }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

  在Startup中使用:

// Startup.cs
  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
      app.UseTestMiddleware();
  }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

 

补充:NetCore的学习地址https://docs.microsoft.com/zh-cn/aspnet/core/?view=aspnetcore-6.0


作者:꧁执笔小白꧂