当前位置: 首页 > 科技观察

如何在ASP.NetCore中使用条件中间件

时间:2023-03-14 22:50:34 科技观察

ASP.NetCore是微软开源的跨平台、可扩展、轻量级、模块化的框架,可用于构建高性能的Web应用程序。可以在ASP.NetCore请求管道中注入中间件组件来自定义和修改Request和Response。ASP.NetCore中间件可用于检查、路由或修改管道中流动的请求和响应。本文将讨论如何使用这些中间件来实现一些高级操作。Use、Run、Map方法简介Use、Map和Run方法通常用于一起构建HTTPPipeline管道。让我们快速浏览一下这些方法及其用途。使用该方法会执行一个delegate,然后将交接棒传递给Pipeline的下一个中间件。因为这个方法暂时拥有交接棒,所以这个方法可以用于短路操作。Run方法执行委托并返回结果。Map方法将有条件地执行委托并返回结果。注册中间件中间件注册在Startup.Configure中,调用方法为Use*系列扩展方法。注册中间件的语法如下。publicvoidConfigure(IApplicationBuilderapp,IHostingEnvironmentenv){app.UseMyCustomMiddleware();}需要注意的是,中间件的执行顺序与你注册的顺序一致。Invoke方法每个中间件都包含一个Invoke()方法。该方法的参数是HttpContext的一个实例。这个中间件的业务逻辑会在下一个中间件执行前后执行。如果你有点迷茫,可以看看什么是递归调用,如下代码注释所示:nextmiddlewareiscalled}pipeline扩展方法:映射HtMap和Map时,它们常被用来对pipeline操作进行导流,前者基于Request路径,后者基于指定谓词动词。以下代码片段显示了如何使用Map方法拆分请求管道。publicclassStartup{privatestaticvoidMapRequestA(IApplicationBuilderapp){app.Run(asynccontext=>{awaitcontext.Response.WriteAsync("ThisisMapRequestA");});}privatestaticvoidMapRequestB(IApplicationBuilderapp){app.Run(asynccontext=>{awaitcontext.Response.WriteAsyncThisisMapRequestB");});}privatestaticvoidMapRequestC(IApplicationBuilderapp){app.Run(asynccontext=>{awaitcontext.Response.WriteAsync("ThisisMapRequestC");});}publicvoidConfigure(IApplicationBuilderapp){app.Map("/mapRequestPathA",MapRequestA);app.Map("/mapRequestPathB",MapRequestB);app.Map("/mapRequestPathB",MapRequestC);app.Run(asynccontext=>{awaitcontext.Response.WriteAsync("HelloWorld!");});}//Othermethods}MapWhen方法接受两个参数:Funcpredicatedelegateaction你可以在Startup.Configure方法中拒绝text/xml格式的请求,如下代码所示:publicvoidConfigure(IApplicationBuilderapp,IHostingEnvironmentenv){if(env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.MapWhen(context=>context.Request.ContentType.Equals("text/xml",StringComparison.InvariantCultureIgnoreCase),(IApplicationBuilderapplicationBuilder)=>{applicationBuilder.Run(asynccontext=>{awaitTask.FromResult(context.Response.StatusCode=StatusCodes.Status406NotAcceptable);});});app.UseMvc();}使用UseWhenUseWhen方法可以有条件地执行中间件,代码如下fragment显示如果当前Request请求路径以/api开头,则执行指定的中间件,代码如下:app.UseWhen(context=>context.Request.Path.StartsWithSegments("/api"),applicationBuilder=>{applicationBuilder.UseCustomMiddleware();});请注意,UseWhen不像MapWhen,前者会继续执行后面的中间件逻辑,而不管当前UseWhen委托函数返回true还是false,如果你有点迷糊,可以理解如下代码:app.UseMiddlewareA();app.UseWhen(context=>context.Request.Path.StartsWithSegments("/api"),applicationBuilder=>{applicationBuilder.UseMiddlewareB();});app.UseMiddlewareC();如果中间没有短路,那么中间件A和C肯定会被执行,而当请求路径以/api开头时,中间件B也会被调度在ASP.NetCore请求处理管道中有一个中间件链,所有请求和响应都通过它流动,当新请求到达时,这些中间件要么处理请求,要么将其传递给管道中的下一个组件,了解更多复杂的请求处理,我们可以使用Map和MapWhen方法拆分管道,使用UseWhen有条件地执行中间件。翻译链接:https://www.infoworld.com/article/3429602/how-to-use-conditional-middleware-in-aspnet-core.html