常规中间件(Conventional Middleware) 之 自定义中间件
//1 定义个中间件类
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
await _next(context);
await context.Response.WriteAsync("custom 1");
}
}
//通过IApplicationBuilder的扩展方法暴露中间件
public static class MiddlewareExtends
{
public static IApplicationBuilder MyMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<MyMiddleware>();
}
}
2 注册到请求处理管道中
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.MyMiddleware();
}
---------------------------------------
注意事项:middleware中必须包含一个名称为Invoke或InvokeAsync的公共实例方法,且方法的第一个参数必须是HttpContext 类型