向 Startup.Configure 方法添加中间件组件的顺序定义了针对请求调用这些组件的顺序,以及响应的相反顺序。 此顺序对于安全性、性能和功能至关重要。
创建中间件有多种方式
- 工厂模式
- 约定模式
- Startup.Configure方法中直接 IApplicationBuilder.Use()
这种方式无须创建扩展以及IServiceCollection注入,框架自动Build()
工厂模式
使用 MiddlewareFactory 激活的中间件:
public class FactoryActivatedMiddleware:IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
await context.Response.WriteAsync("middleware1 in");
await next.Invoke(context);
await context.Response.WriteAsync("middleware1 out");
}
}
为中间件创建扩展:
public static IApplicationBuilder UserMiddleware1(this IApplicationBuilder builder)
{
return builder.UseMiddleware<FactoryActivatedMiddleware>();
}
将工厂激活的中间件添加到 Startup.ConfigureServices 的内置容器中:
services.AddTransient<FactoryActivatedMiddleware>();
在 Startup.Configure 的请求处理管道中注册:
app.UserMiddleware1();
约定模式
通过依赖注入的方式激活中间件
public class ConventionalMiddleware
{
private readonly RequestDelegate _next;
public ConventionalMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
await context.Response.WriteAsync("middleware2 in");
await _next.Invoke(context);
await context.Response.WriteAsync("middleware2 out");
}
}
为中间件创建扩展:
public static IApplicationBuilder UseFactoryActivatedMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<FactoryActivatedMiddleware>();
}
在 Startup.Configure 的请求处理管道中注册:
app.UseConventionalMiddleware();
简单方式
app.Use(async (context, next) => await context.Response.WriteAsync("middleware3"));
管道顺序
app.UseFactoryActivatedMiddleware();
app.UseConventionalMiddleware();
app.Use(async (context, next) => await context.Response.WriteAsync("middleware in "));
执行结果:
middleware1 in
middleware2 in
middleware3
middleware2 out
middleware1 out
网友评论