其他分享
首页 > 其他分享> > 常规中间件(Conventional Middleware) 之 自定义中间件

常规中间件(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");
  }

}

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的公共实例方法

 

标签:Conventional,自定义,中间件,IApplicationBuilder,next,MyMiddleware,context,public
来源: https://www.cnblogs.com/xiaonanmu/p/14220487.html