2017-12-27 2670 views
0

什么时候使用Map和MapWhen在我们正在验证请求的时候在asp.net核心中间件中分支。Map和MapWhen在asp.net核心中间件中的区别?

public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
    { 

     app.Map("", (appBuilder) => 
     { 
      appBuilder.Run(async (context) => { 

       await context.Response.WriteAsync(""); 
      }); 
     }); 

     app.MapWhen(context => context.Request.Query.ContainsKey(""), (appBuilder) => 
     { 
      appBuilder.Run(async (context) => 
      { 
       await context.Response.WriteAsync(""); 
      }); 

     }); 
    } 

回答

2

Map只能根据指定的请求路径的匹配来分支请求。 MapWhen功能更强大,并允许根据与当前对象一起运行的指定谓词的结果来分支请求。 到目前为止HttpContext包含有关HTTP请求的所有信息,MapWhen允许您使用非常特定的条件来分支请求管道。

任何Map呼叫可以很容易地转换为MapWhen,但反之亦然。例如,这Map电话:

app.Map("SomePathMatch", (appBuilder) => 
{ 
    appBuilder.Run(async (context) => { 

     await context.Response.WriteAsync(""); 
    }); 
}); 

等同于以下MapWhen电话:

app.MapWhen(context => context.Request.Path.StartsWithSegments("SomePathMatch"), (appBuilder) => 
{ 
    appBuilder.Run(async (context) => 
    { 
     await context.Response.WriteAsync(""); 
    }); 
}); 

所以回答你的问题“何时使用地图和MapWhen分支”:当您根据分行要求使用Map请求路径。基于来自HTTP请求的其他数据转移请求时,请使用MapWhen

相关问题