强类型约束的中间件(IMiddleware)
上代码
1. 自定义一个中间件
public class MyMiddleware2 : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
await next(context);
await context.Response.WriteAsync("custom 2");
}
}
public static class MiddlewareExtends
{
public static IApplicationBuilder MyMiddleware2(this IApplicationBuilder builder)
{
return builder.UseMiddleware<MyMiddleware2>();
}
}
2. 注册到容器中
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<MyMiddleware2>();
}
3. 进入请求处理管道
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.MyMiddleware2();
}
注意:一定要将自定义的中间件注册到容器中,不然会报错。