如何使用ASP.Net Core中的条件中间件?

译文
开发 后端
使用ASP.Net Core中的中间件时,应充分利用条件分支等高级操作。

 

[[273129]]

【51CTO.com快译】ASP.Net Core是微软的一种开源跨平台框架,具有可扩展、精简化和模块化的优点,可用于构建高性能Web应用程序。中间件组件可以用在ASP.Net Core请求管道中,定制处理请求和响应的方式。

ASP.Net Core中间件组件还可用于检查、路由或修改流经管道的请求和响应消息。本文讨论了如何用ASP.Net Core中的中间件执行一些高级操作。

创建ASP.Net Core MVC项目

首先,不妨在Visual Studio中创建一个ASP.Net Core项目。假设你的系统中已安装Visual Studio 2017或Visual Studio 2019,按照下列步骤,在Visual Studio中创建一个新的ASP.Net Core项目。

  1. 启动Visual Studio IDE。
  2. 点击“创建新项目”。
  3. 在“创建新项目”窗口中,从显示的模板列表中选择“ASP.Net Core Web应用程序”。
  4. 点击“下一步”。
  5. 在“配置新项目”窗口中,指定新项目的名称和位置。
  6. 点击“创建”。
  7. 在接下来显示的“创建新的ASP.Net Core Web应用程序”中,从顶部的下拉列表中选择.Net Core作为运行时环境和ASP.Net Core 2.2(或更高版本)。
  8. 选择“Web应用程序(模型-视图-控制器)”作为项目模板,创建一个新的ASP.Net Core应用程序。
  9. 确保“启用Docker支持”和“针对HTTPS的配置”复选框未勾选,因为我们在此处不会使用那些功能。
  10. 确保身份验证设置为“无身份验证”,因为我们也不会使用身份验证。
  11. 点击“创建”。

遵循这些步骤应该可以在Visual Studio中创建一个新的ASP.Net Core项目。我们将在本文的后续部分中使用该项目。

ASP.Net Core中的Use、Run和Map等方法

Use、Map和Run等方法用于在ASP.Net Core中配置HTTP管道。下面简要介绍这每个方法及用途。

  • Use——该方法将执行委托(delegate),然后进入到管道中的下一步。Use方法还可用于使管道短路。
  • Run——该方法将执行委托并返回结果。
  • Map——该方法将有条件地执行委托并返回结果。

ASP.Net Core中注册中间件

ASP.Net Core中的中间件组件在Startup类的Configure方法中注册。Use *扩展方法用于注册中间件。下面是注册中间件组件的语法。 

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  2.  
  3. app.UseMyCustomMiddleware();  

值得一提的是,中间件组件按它们注册的顺序来加以执行。

ASP.Net Core中的Invoke方法

每个中间件组件都包含一个Invoke方法。该方法接受对HttpContext实例的引用作为实参。中间件组件可以在调用下一个中间件组件前后执行操作。下面是典型的Invoke方法的示例: 

  1. public async Task Invoke(HttpContext context)  
  2.  
  3. // Write code here that will be executed before the  
  4. // next middleware is called  
  5. await _next.Invoke(context); // call next middleware  
  6. // Write code here that will be executed after the  
  7. //next middleware is called  

ASP.Net Core中使HTTP管道分支

Map扩展方法(即Map和MapWhen)用于使管道分支。Map用于基于特定的请求路径来分支,而MapWhen用于基于特定断言的结果来分支。

下列代码片段表明了Map方法如何用于使请求管道分支。 

  1. public class Startup  
  2.  
  3. private static void MapRequestA(IApplicationBuilder app)  
  4.  
  5. app.Run(async context =>  
  6.  
  7. await context.Response.WriteAsync("This is MapRequestA");  
  8. });  
  9.  
  10. private static void MapRequestB(IApplicationBuilder app)  
  11.  
  12. app.Run(async context =>  
  13.  
  14. await context.Response.WriteAsync("This is MapRequestB");  
  15. });  
  16.  
  17. private static void MapRequestC(IApplicationBuilder app)  
  18.  
  19. app.Run(async context =>  
  20.  
  21. await context.Response.WriteAsync("This is MapRequestC");  
  22. });  
  23.  
  24. public void Configure(IApplicationBuilder app)  
  25.  
  26. app.Map("/mapRequestPathA", MapRequestA);  
  27. app.Map("/mapRequestPathB", MapRequestB);  
  28. app.Map("/mapRequestPathB", MapRequestC);  
  29. app.Run(async context =>  
  30.  
  31. await context.Response.WriteAsync("Hello World!");  
  32. });  
  33.  
  34. //Other methods  

MapWhen方法接受两个参数:

  • Func
  • 委托操作

你可以在Startup类的Configure方法中使用下列代码片段,不允许内容类型“text/html”。 

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  2.  
  3. if (env.IsDevelopment())  
  4.  
  5. app.UseDeveloperExceptionPage();  
  6.  
  7. app.MapWhen(context => context.Request.ContentType.Equals  
  8. ("text/xml", StringComparison.InvariantCultureIgnoreCase),  
  9. (IApplicationBuilder applicationBuilder) =>  
  10.  
  11. applicationBuilder.Run(async context =>  
  12.  
  13. await Task.FromResult(context.Response.StatusCode = StatusCodes.Status406NotAcceptable);  
  14. });  
  15. });  
  16. app.UseMvc();  

ASP.Net Core中的UseWhen方法

UseWhen方法可用于有条件地执行中间件。下列代码片段表明了如果请求路径以“/api”开头,UseWhen方法如何用于执行中间件组件。 

  1. app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), applicationBuilder =>  
  2.  
  3. applicationBuilder.UseCustomMiddleware();  
  4. }); 

请注意:与MapWhen不同,UseWhen方法继续执行后一个中间件,不管UseWhen断言是真还是假。不妨通过示例了解这一点。考虑下面这部分代码: 

  1. app.UseMiddlewareA(); 
  2. app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), applicationBuilder =>  
  3.  
  4. applicationBuilder.UseMiddlewareB();  
  5. });  
  6. app.UseMiddlewareC(); 

如果中间件没有短路,中间件A和C将始终执行。只有请求路径以“/api”开关,中间件B才会执行。

在ASP.Net Core中,请求处理管道中有一连串中间件组件。所有请求和响应都流经该管道。新请求进入后,这些中间件组件或处理请求,或将请求传递到管道中的下一个组件。想完成更复杂的请求处理,我们可以使用Map和MapWhen方法使管道分支,使用UseWhen有条件地执行中间件。

【51CTO译稿,合作站点转载请注明原文译者和出处为51CTO.com】

责任编辑:庞桂玉 来源: 51CTO
相关推荐

2021-01-26 14:57:00

中间件应用模块化

2023-10-18 07:32:27

中间件技术HTTP请求

2021-02-02 16:19:08

Serilog日志框架

2021-02-06 21:40:13

SignalR通讯TypeScript

2021-03-17 09:45:31

LazyCacheWindows

2021-01-28 22:39:35

LoggerMessa开源框架

2021-01-31 22:56:50

FromServiceASP

2021-02-28 20:56:37

NCache缓存框架

2021-03-03 22:37:16

MediatR中介者模式

2021-03-10 09:40:43

LamarASP容器

2021-01-07 07:39:07

工具接口 Swagger

2021-02-03 13:35:25

ASPweb程序

2021-02-19 06:54:33

配置系统ASP.NET Cor

2020-08-19 08:39:05

中间件前端设计模式

2021-02-07 17:29:04

监视文件接口

2021-03-04 11:10:29

容器化Docker虚拟机

2021-01-04 05:44:54

框架日志

2021-01-11 05:20:05

Controller代码数据层

2022-08-01 08:00:00

开发工具跟踪侦听器

2021-01-05 07:51:06

版本化ASP
点赞
收藏

51CTO技术栈公众号