ASP.NETCore-中间件Middleware_编写中间件_NET5

1、编写中间件

①方式一(中间件写在Startup.cs中)

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  app.Use(async (context, next) =>
  {
    // TO DO
    await next();
  });
} 

②方式二(中间件写在独立文件中)

  中间件写法:

 public class TestMiddleware
    {
        private readonly RequestDelegate _next;

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

        public Task Invoke(HttpContext httpContext)
        {
            // TO DO
            return _next(httpContext);
        }
    }

  注册到IApplicationBuilder:

    public static class TestMiddlewareExtensions
    {
        public static IApplicationBuilder UseTestMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<TestMiddleware>();
        }
    }

  在Startup中使用:

  // Startup.cs
  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
      app.UseTestMiddleware();
  }

 

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

posted @ 2022-01-27 16:42  ꧁执笔小白꧂  阅读(286)  评论(0)    收藏  举报