在 .net 核心应用程序启动中使用 MapWhen 和 ApplicationBuilder

是否可以进行部分分支启动?


例如,是否有可能有类似的东西:


public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

    app.AlwaysUseThisMiddleware();

    app.MapWhen(conditionA, appBuilder => {appBuilder.SometimesUseThisOne;})

    app.MapWhen(conditionB, appBuilder => {appBuilder.SometimesUseThisOtherOne;})

还是我需要把AlwaysUseThisMiddleware每个分支放在里面?像这样:


public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

    app.MapWhen(conditionA, appBuilder =>

    {

        appBuilder.AlwaysUseThisMiddleware(); // Duplicated

        appBuilder.SometimesUseThisOne;

    )

    app.MapWhen(conditionB, appBuilder =>

    {

        appBuilder.AlwaysUseThisMiddleware(); // Duplicated

        appBuilder.SometimesUseThisOtherOne;

    )


繁花不似锦
浏览 119回答 1
1回答

动漫人物

简短的回答:是的。它将按您的预期工作。实际上,当我们Use()一系列中间件的时候,我们就是在注册一系列中间件,这些中间件在处理请求时会依次调用。该MapWhen()方法只不过是调用Use(). 什么MapWhen(predicate,configFn)是注册运行如下的东西:if (predicate(context)){&nbsp; &nbsp; await branch(context);} else {&nbsp; &nbsp; await _next(context);}结果,当我们调用 时MapWhen(),我们正在注册另一个分支处理的中间件。例如 :app.UseMiddleware<AlwaysUseThisMiddleware>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;app.MapWhen(ctx=>ctx.Request.Query["a"]=="1", appBuilder =>{&nbsp; &nbsp; appBuilder.UseMiddleware<SometimesUseThisOne>();});app.MapWhen(ctx=>ctx.Request.Query["b"]=="1", appBuilder =>{&nbsp; &nbsp; appBuilder.UseMiddleware<SometimesUseThisOtherOne>();})// ...基本上,此代码以以下方式运行:call&nbsp; `AlwaysUseThisMiddleware`;////////////////////////////////////if (ctx.Request.Query["a"]=="1"){&nbsp; &nbsp;&nbsp; &nbsp; call SometimesUseThisOne ;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;} else {&nbsp; &nbsp; //------------------------------------------&nbsp; &nbsp; if (ctx.Request.Query["b"]=="1"){&nbsp; &nbsp; &nbsp; &nbsp; call SometimesUseThisOtherOne ;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; //##################################################&nbsp; &nbsp; &nbsp; &nbsp; await _next(context);&nbsp; // call other middlewares ...&nbsp; &nbsp; &nbsp; &nbsp; //##################################################&nbsp; &nbsp; }&nbsp; &nbsp; //-----------------------------------------}////////////////////////////////////或者,如果您愿意,也可以将其重写如下:call `AlwaysUseThisMiddleware` middlewareif(ctx.Request.Query["a"]=="1")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// go to branch 1&nbsp; &nbsp; call `SometimesUseThisOne` middlewareelse if (ctx.Request.Query["b"]=="1")&nbsp; &nbsp; &nbsp;// go to branch 2&nbsp; &nbsp; call `SometimesUseThisOtherOne` middleware&nbsp;else :&nbsp; &nbsp; ...注意这里是一个分支else if而不是if. 并且中间件AlwaysUseThisMiddleware 总是在 branch1 & branch2 之前调用。
打开App,查看更多内容
随时随地看视频慕课网APP