Asp.Net Core 查漏补缺《一》 —— IStartFilter

Asp.Net Core 查漏补缺《一》 —— IStartFilter

 

IStartFilter 实现了Configure,如下图一,而Configure方法接受并返回Action<IApplicationBuilder> 如图二,IApplicationBuilder是用于定义配置应用请求管道的。

 

(图一)

 

 

 

(图二)

下面就让我们动手尝试一把


1.1 定义中间件类 StartFilterMiddleware

public class StartFilterMiddlerware
     {
         private readonly RequestDelegate _next;
         private int _count;
         public StartFilterMiddlerware(RequestDelegate next)
         {
             _next = next;
         }
 ​
         public async Task Invoke(HttpContext httpContext)
         {
             ++_count;
             Console.WriteLine($"第{_count} 次 调用 IStartFilter");
             await _next(httpContext);
         }
     }

 

1.2 添加AjuStartFilter 类

让 AjuStartFilter 类继承于 IStartFilter,在Configure 方法中 使用 StartFilterMiddleare :

 public class AjuStartFilter : IStartupFilter
     {
         public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
         {
             return builder =>
             {
                 builder.UseMiddleware<StartFilterMiddlerware>();
                 next(builder);
             };
         }
     }

 

1.3 启用

注意: 1.3.1 和 1.3.2 任选其一

1.3.1 在 Program 类中启用
 
public class Program
     {
         public static void Main(string[] args)
         {
             CreateHostBuilder(args).Build().Run();
         }
 ​
         public static IHostBuilder CreateHostBuilder(string[] args) =>
             Host.CreateDefaultBuilder(args)
              .ConfigureServices(server =>
              {
                  server.AddTransient<IStartupFilter, AjuStartFilter>();
              }).ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
            ;
     }

 

1.3.2 在StartUp 的 ConfigureServices 方法中启用
  public class Startup
     {
         public void ConfigureServices(IServiceCollection services)
         {
             services.AddTransient<IStartupFilter, AjuStartFilter>();
         }
  }

 

1.4 结果

 

 

 

posted @ 2020-10-23 16:42  ZerekZhang  阅读(253)  评论(0编辑  收藏  举报