[.net core]9.中间件的具体实现
阅读原文时间:2023年07月14日阅读:2

查看Startup.cs的configure方法

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
    {  
        if (env.IsDevelopment())  
        {  
            app.UseDeveloperExceptionPage();  
        }

        app.Run(async (context) =>  
        {  
            await context.Response.WriteAsync(\_config\["MyKey"\]);  
        });  
    }

修改成

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
    {  
        if (env.IsDevelopment())  
        {  
            app.UseDeveloperExceptionPage();  
        }

        app.Use(async (context, next) =>  
        {  
            Console.WriteLine("步骤1:中间件1处理");  
            await next();  
            Console.WriteLine("步骤7:中间件1响应回调");

        });

        app.Use(async (context, next) =>  
        {  
            Console.WriteLine("步骤2:中间件2处理");  
            await next();  
            Console.WriteLine("步骤6:中间件2响应回调");

        });  
        app.Use(async (context, next) =>  
        {  
            Console.WriteLine("步骤3:中间件3处理");  
            await next();  
            Console.WriteLine("步骤5:中间件3响应回调");

        });

        app.Run(async (context) =>  
        {  
            //在这里产生响应  
            await context.Response.WriteAsync("产生响应");  
            Console.WriteLine("步骤4:响应回调");  
        });  
    }

由于我是consola.writeLine();所以选择只开启kestrel

ctrl+f5 看效果

乱码了,  在respon 前面加一行代码

            context.Response.Headers\["Content-Type"\] = "application/json";

显示正常

,看控件台输出我们可以知道中间件消息传递的过程