asp.net Core自定义 管道中间件

整个 asp.Net Core应用都是在 管道中运行的,管道中放的都是中间件。下面是自定义中间件的两种方法

方法一
public class TestMiddleware
{//转载请保留 http://www.luofenming.com/show.aspx?id=ART2020021200001
    private readonly RequestDelegate _next;
    public TestMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task Invoke(HttpContext context)
    {
        await Task.Run(() => Console.WriteLine("测试中间件"));//这是中间件要完成的事件

        await _next(context);//这是把 context传递给下一个中间件
    }
}
下面中间使用 在Startup类 Configure里面应用中间件
app.UseMiddleware<TestMiddleware>();
方法二(直接在Startup类 Configure里面写,并应用)
app.Use(async (context, next) =>
{
    await Task.Run(() => Console.WriteLine("测试中间件2"));
    await next();
});


在此扩展一下,Startup类 ConfigureServices里面添加的都是 中间件所依赖的类,需要才注册到容器里面