NetCore消息管道 Middleware
中间件定义
/// <summary> /// 自定义中间件1 /// </summary> public class MyMiddleware : IMiddleware { public async Task InvokeAsync(HttpContext context, RequestDelegate next) { Console.WriteLine("MyMiddleware_1,开始处理"); await next.Invoke(context); Console.WriteLine("MyMiddleware_1,结束"); } } /// <summary> /// 自定义中间件2 /// </summary> public class MyMiddleware2 : IMiddleware { public async Task InvokeAsync(HttpContext context, RequestDelegate next) { Console.WriteLine("MyMiddleware_2,开始处理"); await next.Invoke(context); Console.WriteLine("MyMiddleware_2,结束"); } } /// <summary> /// 通过拓展方法调用 /// </summary> public static class Middleware2AppBuilderExtensions { public static IApplicationBuilder UseMiddleware2(this IApplicationBuilder app) { return app.UseMiddleware<MyMiddleware2>(); } }
中间件注册
//注入中间件 builder.Services.AddSingleton<MyMiddleware>(); builder.Services.AddSingleton<MyMiddleware2>();
消息管道中加入中间件处理
//UseMiddleware方式调用 app.UseMiddleware<MyMiddleware>(); //拓展方式调用 app.UseMiddleware2(); //Use方式加入处理逻辑到消息管道 app.Use(async (context, next) => { // await context.Response.WriteAsync("Begin Custom Middleward"); Console.WriteLine("Begin Custom Middleward"); await next.Invoke(); // await context.Response.WriteAsync("End Custom Middleward"); Console.WriteLine("End Custom Middleward"); }); //Run方式作为处理终结点,不再调用下一个middleward app.Run(async (context) => { //await context.Response.WriteAsync("Middleward EndPoint"); Console.WriteLine("Middleward EndPoint"); });
运行结果
喜欢 C#、SQL、Web