常规中间件(Conventional Middleware) 之 内联中间件(in-line middleware)

可以使用Run, Map, Use,MapWhen,UseWhen 等扩展方法来实现。

简单介绍下,这几个方法的区别:

1 有回路,意思是请求可以接着往下执行,然后原路返回。

Use, UseWhen

2 无回路,请求到当前为止

Run,Map,MapWhen

下面来个小案例

在Startup文件中的

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
  }


  app.Use( async(context,next)=> {
    await next();
    await context.Response.WriteAsync("1");
  });

  app.UseWhen(context => {
    return context.Request.Query.Keys.Contains("a");
  }, builder =>
  {
    builder.Use(async (context, next) => {
      await next();
      await context.Response.WriteAsync("2");
    });
  });

  app.Map("/k", builder =>
  {
    builder.Use(async (c, n) =>
    {
      await n();
      await c.Response.WriteAsync("3");
    });

  });

  app.MapWhen(context => {
    return context.Request.Query.Keys.Contains("b");
  }, builder =>
  {
    builder.Run(async c =>
    {
      await c.Response.WriteAsync("4");
    });
  });

  app.Run(async c =>
  {
    await c.Response.WriteAsync("5");
  });

  //省略其他……

}

试试各种不同的输出

http://localhost:5000/

51

http://localhost:5000/?a=1

521

http://localhost:5000/k

31

http://localhost:5000/k?a=1

321

http://localhost:5000/k?a=1&b=1

321

http://localhost:5000/?a=1&b=1

421

http://localhost:5000/k?b=1

31

----------------------------

小提示: Map或MapWhen里面 可以使用多个Use方法和一个Run方法

原文地址:https://www.cnblogs.com/xiaonanmu/p/14220425.html