1 回答

TA貢獻1815條經(jīng)驗 獲得超10個贊
簡短的回答:
是的。它將按您的預期工作。
實際上,當我們Use()一系列中間件的時候,我們就是在注冊一系列中間件,這些中間件在處理請求時會依次調(diào)用。
該MapWhen()方法只不過是調(diào)用Use(). 什么MapWhen(predicate,configFn)是注冊運行如下的東西:
if (predicate(context)){
await branch(context);
} else {
await _next(context);
}
結果,當我們調(diào)用 時MapWhen(),我們正在注冊另一個分支處理的中間件。
例如 :
app.UseMiddleware<AlwaysUseThisMiddleware>();
app.MapWhen(ctx=>ctx.Request.Query["a"]=="1", appBuilder =>{
appBuilder.UseMiddleware<SometimesUseThisOne>();
});
app.MapWhen(ctx=>ctx.Request.Query["b"]=="1", appBuilder =>{
appBuilder.UseMiddleware<SometimesUseThisOtherOne>();
})
// ...
基本上,此代碼以以下方式運行:
call `AlwaysUseThisMiddleware`;
////////////////////////////////////
if (ctx.Request.Query["a"]=="1"){
call SometimesUseThisOne ;
} else {
//------------------------------------------
if (ctx.Request.Query["b"]=="1"){
call SometimesUseThisOtherOne ;
} else {
//##################################################
await _next(context); // call other middlewares ...
//##################################################
}
//-----------------------------------------
}
////////////////////////////////////
或者,如果您愿意,也可以將其重寫如下:
call `AlwaysUseThisMiddleware` middleware
if(ctx.Request.Query["a"]=="1") // go to branch 1
call `SometimesUseThisOne` middleware
else if (ctx.Request.Query["b"]=="1") // go to branch 2
call `SometimesUseThisOtherOne` middleware
else :
...
注意這里是一個分支else if而不是if. 并且中間件AlwaysUseThisMiddleware 總是在 branch1 & branch2 之前調(diào)用。
- 1 回答
- 0 關注
- 80 瀏覽
添加回答
舉報