1.前言
整个http request请求跟http response返回结果之间的处理流程是一个请求管道(request pipeline)。而中间件(middleware)则是一种装配到请求管道以处理请求和响应的组件。每个组件:
- 可选择是否将请求传递到管道中的下一个组件。
- 可在管道中的下一个组件前后执行工作。
中间件(middleware)处理流程如下图所示:
2.使用中间件
asp.net core请求管道中每个中间件都包含一系列的请求委托(request delegates)来处理每个http请求,依次调用。请求委托通过使用iapplicationbuilder类型的run、use和map扩展方法在strartup.configure方法中配置。下面我们通过配置run、use和map扩展方法示例来了解下中间件。
2.1 run
public class startup { public void configure(iapplicationbuilder app) { //第一个请求委托run app.run(async context =>//内嵌匿名方法 { await context.response.writeasync("hello, world!"); }); //第二个请求委托run app.run(async context =>//内嵌匿名方法 { await context.response.writeasync("hey, world!"); }); } }
响应结果:
由上述代码可知,run方法指定为一个内嵌匿名方法(称为并行中间件,in-line middleware),而内嵌匿名方法中并没有指定执行下一个请求委托,这一个过程叫管道短路,而该中间件又叫“终端中间件”(terminal middleware),因为它阻止中间件下一步处理请求。所以在run第一个请求委托的时候就已经终止请求,并没有执行第二个请求委托直接返回hello, world!输出文本。而根据官网解释,run是一种约定,有些中间件组件可能会暴露他们自己的run方法,而这些方法只能在管道末尾处运行(也就是说run方法只在中间件执行最后一个请求委托时才使用)。
2.2 use
public void configure(iapplicationbuilder app) { app.use(async (context, next) => { context.response.contenttype = "text/plain; charset=utf-8"; await context.response.writeasync("进入第一个委托 执行下一个委托之前\r\n"); //调用管道中的下一个委托 await next.invoke(); await context.response.writeasync("结束第一个委托 执行下一个委托之后\r\n"); }); app.run(async context => { await context.response.writeasync("进入第二个委托\r\n"); await context.response.writeasync("hello from 2nd delegate.\r\n"); await context.response.writeasync("结束第二个委托\r\n"); }); }
响应结果:
由上述代码可知,use方法将多个请求委托链接在一起。而next参数表示管道中的下一个委托。如果不调用next参数调用下一个请求委托则会使管道短路。比如,一个授权(authorization)中间件只有通过身份验证之后才能调用下一个委托,否则它就会被短路,并返回“not authorized”的响应。所以应尽早在管道中调用异常处理委托,这样它们就能捕获在管道的后期阶段发生的异常。
2.3 map和mapwhen
- map:map扩展基于请求路径创建管道分支。
- mapwhen:mapwhen扩展基于请求条件创建管道分支。
map示例:
public class startup { private static void handlemaptest1(iapplicationbuilder app) { app.run(async context => { await context.response.writeasync("map test 1"); }); } private static void handlemaptest2(iapplicationbuilder app) { app.run(async context => { await context.response.writeasync("map test 2"); }); } public void configure(iapplicationbuilder app) { app.map("/map1", handlemaptest1); app.map("/map2", handlemaptest2); app.run(async context => { await context.response.writeasync("hello from non-map delegate. <p>"); }); } }
下面表格使用前面的代码显示来自http://localhost:5001的请求和响应。
请求 | 响应 |
localhost:5001 | hello from non-map delegate. |
localhost:5001/map1 | map test 1 |
localhost:5001/map2 | map test 2 |
localhost:5001/map3 | hello from non-map delegate. |
由上述代码可知,map方法将从httprequest.path中删除匹配的路径段,并针对每个请求将该路径追加到httprequest.pathbase。也就是说当我们在浏览器上输入map1请求地址的时候,系统会执行map1分支管道输出其请求委托信息,同理执行map2就会输出对应请求委托信息。
mapwhen示例:
public class startup { private static void handlebranch(iapplicationbuilder app) { app.run(async context => { var branchver = context.request.query["branch"]; await context.response.writeasync($"branch used = {branchver}"); }); } public void configure(iapplicationbuilder app) { app.mapwhen(context => context.request.query.containskey("branch"), handlebranch); app.run(async context => { await context.response.writeasync("hello from non-map delegate. <p>"); }); } }
下面表格使用前面的代码显示来自http://localhost:5001的请求和响应。
请求 | 响应 |
http://localhost:5001 | hello from non-map delegate. <p> |
https://localhost:5001/?branch=master | branch used = master |
由上述代码可知,mapwhen是基于branch条件而创建管道分支的,我们在branch条件上输入master就会创建其对应管道分支。也就是说,branch条件上输入任何一个字符串条件,都会创建一个新的管理分支。
而且还map支持嵌套,例如:
public void configure(iapplicationbuilder app) { app.map("/level1", level1app => { level1app.map("/level2a", level2aapp => { // "/level1/level2a" processing }); level1app.map("/level2b", level2bapp => { // "/level1/level2b" processing }); }); }
还可同时匹配多个段:
public class startup { private static void handlemultiseg(iapplicationbuilder app) { app.run(async context => { await context.response.writeasync("map multiple segments."); }); } public void configure(iapplicationbuilder app) { app.map("/map1/seg1", handlemultiseg); app.run(async context => { await context.response.writeasync("hello from non-map delegate."); }); } }
3.顺序
向startup.configure方法添加中间件组件的顺序定义了在请求上调用它们的顺序,以及响应的相反顺序。此排序对于安全性、性能和功能至关重要。
以下startup.configure方法将为常见应用方案添加中间件组件:
- 异常/错误处理(exception/error handling)
- http严格传输安全协议(http strict transport security protocol)
- https重定向(https redirection)
- 静态文件服务器(static file server)
- cookie策略实施(cookie policy enforcement)
- 身份验证(authentication)
- 会话(session)
- mvc
请看如下代码:
public void configure(iapplicationbuilder app) { if (env.isdevelopment()) { // when the app runs in the development environment: // use the developer exception page to report app runtime errors. // use the database error page to report database runtime errors. app.usedeveloperexceptionpage(); app.usedatabaseerrorpage(); } else { // when the app doesn't run in the development environment: // enable the exception handler middleware to catch exceptions // thrown in the following middlewares. // use the http strict transport security protocol (hsts) // middleware. app.useexceptionhandler("/error"); app.usehsts(); } // return static files and end the pipeline. app.usestaticfiles(); // authenticate before the user accesses secure resources. app.useauthentication(); }
从上述示例代码中,每个中间件扩展方法都通过microsoft.aspnetcore.builder命名空间在 iapplicationbuilder上公开。但是为什么我们要按照这个顺序去添加中间件组件呢?下面我们挑几个中间件来了解下。
- useexceptionhandler(异常/错误处理)是添加到管道的第一个中间件组件。因此我们可以捕获在应用程序调用中发生的任何异常。那为什么要将异常/错误处理放在第一位呢?那是因为这样我们就不用担心因前面中间件短路而导致捕获不到整个应用程序所有异常信息。
- usestaticfiles(静态文件)中间件在管道中提前调用,方便它可以处理请求和短路,而无需通过剩余中间组件。也就是说静态文件中间件不用经过useauthentication(身份验证)检查就可以直接访问,即可公开访问由静态文件中间件服务的任何文件,包括wwwroot下的文件。
- useauthentication(身份验证)仅在mvc选择特定的razor页面或controller和action之后才会发生。
经过上面描述,大家都了解中间件顺序的重要性了吧。
4.编写中间件(重点)
虽然asp.net core为我们提供了一组丰富的内置中间件组件,但在某些情况下,你可能需要写入自定义中间件。
4.1中间件类
下面我们自定义一个查询当前区域性的中间件:
public class startup { public void configure(iapplicationbuilder app) { app.use((context, next) => { var culturequery = context.request.query["culture"]; if (!string.isnullorwhitespace(culturequery)) { var culture = new cultureinfo(culturequery); cultureinfo.currentculture = culture; cultureinfo.currentuiculture = culture; } // call the next delegate/middleware in the pipeline return next(); }); app.run(async (context) => { await context.response.writeasync( $"hello {cultureinfo.currentculture.displayname}"); }); } }
可通过传入区域性参数条件进行测试。例如http://localhost:7997/?culture=zh、http://localhost:7997/?culture=en。
但是如果每个自定义中间件都在startup.configure方法中编写如上一大堆代码,那么对于程序来说,将是灾难性的(不利于维护和调用)。为了更好管理代码,我们应该把内嵌匿名方法封装到新建的自定义类(示例自定义requestculturemiddleware类)里面去:
public class requestculturemiddleware { private readonly requestdelegate _next; public requestculturemiddleware(requestdelegate next) { _next = next; } public async task invokeasync(httpcontext context) { context.response.contenttype = "text/plain; charset=utf-8"; var culturequery = context.request.query["culture"]; if (!string.isnullorwhitespace(culturequery)) { var culture = new cultureinfo(culturequery); cultureinfo.currentculture = culture; cultureinfo.currentuiculture = culture; } // call the next delegate/middleware in the pipeline await _next(context); } }
通过startup.configure方法调用中间件:
public class startup { public void configure(iapplicationbuilder app) { app.usemiddleware<requestculturemiddleware>(); app.run(async (context) => { await context.response.writeasync( $"hello {cultureinfo.currentculture.displayname}"); }); } }
4.2中间件扩展方法
startup.configure方法调用中间件设置可以通过自定义的扩展方法将其公开(调用内置iapplicationbuilder公开中间件)。示例创建一个requestculturemiddlewareextensions扩展类并通过iapplicationbuilder公开:
public static class requestculturemiddlewareextensions { public static iapplicationbuilder userequestculture(this iapplicationbuilder builder) { return builder.usemiddleware<requestculturemiddleware>(); } }
再通过startup.configure方法调用中间件:
public class startup { public void configure(iapplicationbuilder app) { app.userequestculture(); app.run(async (context) => { await context.response.writeasync( $"hello {cultureinfo.currentculture.displayname}"); }); } }
响应结果:
通过委托构造中间件,应用程序在运行时创建这个中间件,并将它添加到管道中。这里需要注意的是,中间件的创建是单例的,每个中间件在应用程序生命周期内只有一个实例。那么问题来了,如果我们业务逻辑需要多个实例时,该如何操作呢?请继续往下看。
5.按每次请求创建依赖注入(di)
在中间件的创建过程中,内置的ioc容器会为我们创建一个中间件实例,并且整个应用程序生命周期中只会创建一个该中间件的实例。通常我们的程序不允许这样的注入逻辑。其实,我们可以把中间件理解成业务逻辑的入口,真正的业务逻辑是通过application service层实现的,我们只需要把应用服务注入到invoke方法中即可。asp.net core为我们提供了这种机制,允许我们按照请求进行依赖的注入,也就是每次请求创建一个服务。示例:
public class custommiddleware { private readonly requestdelegate _next; public custommiddleware(requestdelegate next) { _next = next; } // imyscopedservice is injected into invoke public async task invoke(httpcontext httpcontext, imyscopedservice svc) { svc.myproperty(1000); await _next(httpcontext); } } public static class custommiddlewareextensions { public static iapplicationbuilder usecustommiddleware(this iapplicationbuilder builder) { return builder.usemiddleware<custommiddleware>(); } } public interface imyscopedservice { void myproperty(decimal input); } public class myscopedservice : imyscopedservice { public void myproperty(decimal input) { console.writeline("myproperty is " + input); } } public void configureservices(iservicecollection services) { //注入di服务 services.addscoped<imyscopedservice, myscopedservice>(); }
响应结果:
到此这篇关于asp.net core中间件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持代码网。
发表评论