ASP.NET Core 1.0中的管道-中间件模式

ASP.NET Core 1.0借鉴了Katana项目的管道设计(Pipeline)。日志记录、用户认证、MVC等模块都以中间件(Middleware)的方式注册在管道中。显而易见这样的设计非常松耦合并且非常灵活,你可以自己定义任意功能的Middleware注册在管道中。这一设计非常适用于“请求-响应”这样的场景——消息从管道头流入最后反向流出。

在本文中暂且为这种模式起名叫做“管道-中间件(Pipeline-Middleware)”模式吧。

本文将描述”管道-中间件模式”的“契约式”设计和“函数式”设计两种方案。

一、什么是管道-中间件模式?

在此模式中抽象了一个类似管道的概念,所有的组件均以中间件的方式注册在此管道中,当请求进入管道后:中间件依次对请求作出处理,然后从最后一个中间件开始处理响应内容,最终反向流出管道。

二、契约式设计

契约式设计是从面向对象的角度来思考问题,根据管道-中间件的理解,中间件(Middleware)有两个职责:

1
2
3
4
5
public  interface  IMiddleware
{
     Request ProcessRequest(Request request);
     Response ProcessResponse(Response response);
}

管道(Pipeline)抽象应该能够注册中间件(Middleware):

1
2
3
4
5
6
7
8
9
public  interface  IApplicationBuilder
{
     void  Use(IMiddleware middleware);
     void  UseArrange(List<IMiddleware> middlewares);
     Context Run(Context context);
}

实现IApplicationBuilder:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
3 2
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public  class  ApplicationBuilder : IApplicationBuilder
{
     public  IWindsorContainer Container { get ; private  set ; }
     private  readonly  List<IMiddleware> _middlewares;
     public  ApplicationBuilder(IWindsorContainer container)
     {
         Contract.Requires(container!= null , "container!=null" );
         _middlewares= new  List<IMiddleware>();
         Container = container;
     }
     public  void  Use(IMiddleware middleware)
     {
         Contract.Requires(middleware != null , "middleware!=null" );
         _middlewares.Add(middleware);
     }
     public  void  UseArrange(List<IMiddleware> middlewares)
     {
         Contract.Requires(middlewares != null , "middlewares!=null" );
         _middlewares.AddRange(middlewares);
     }
     public  Context Run(Context context)
     {
         Contract.Requires(context!= null , "context!=null" );
         var  request=context.Request;
         var  response=context.Response;
         foreach  ( var  middleware in  _middlewares)
         {
             request = middleware.ProcessRequest(request);
         }
         _middlewares.Reverse();
         foreach  ( var  middleware in  _middlewares)
         {
             response = middleware.ProcessResponse(response);
         }
         return  new  Context(request,response);
     }
}

Run()方法将依次枚举Middleware并对消息的请求和响应进行处理,最后返回最终处理过的消息。

接下来需要实现一个Middleware:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public  class  DefaultMiddleware:IMiddleware
  {
      public  Request ProcessRequest(Request request)
      {
          request.Process( "default request" , "processed by defaultMiddleware" );
          return  request;
      }
      public  Response ProcessResponse(Response response)
      {
          response.Process( "default response" , "processed by defaultMiddleware" );
          return  response;
      }
  }

为了将Middleware注册进管道,我们还可以写一个扩展方法增加代码的可读性:

1
2
3
4
5
6
7
8
9
10
11
12
public  static  void  UseDefaultMiddleware( this  IApplicationBuilder applicationBuilder)
{
     applicationBuilder.Use<DefaultMiddleware>();
}
public  static  void  Use<TMiddleware>( this  IApplicationBuilder applicationBuilder)
     where  TMiddleware:IMiddleware
{
     var  middleware = applicationBuilder.Container.Resolve<TMiddleware>();
     applicationBuilder.Use(middleware);
}

写个测试看看吧:

写第二个Middleware:

1
2
3
4
5
6
7
8
9
10
11
12
13
1 15
16
public  class  GreetingMiddleware:IMiddleware
{
     public  Request ProcessRequest(Request request)
     {
         request.Process( "hello, request" , "processed by greetingMiddleware" );
         return  request;
     }
     public  Response ProcessResponse(Response response)
     {
         response.Process( "hello, request" , "processed by greetingMiddleware" );
         return  response;
     }
}

编写测试:

三、函数式设计方案

此方案也是Owin和ASP.NET Core采用的方案,如果站在面向对象的角度,第一个方案是非常清晰的,管道最终通过枚举所有Middleware来依次处理请求。

站在函数式的角度来看,Middleware可以用Func<Context, Context>来表示,再来看看这张图:

一个Middleware的逻辑可以用Func<Func<Context, Context>, Func<Context, Context>>来表示,整个Middleware的逻辑可以用下面的代码描述:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public  Func<Func<Context, Context>, Func<Context, Context>> Process()
{
     Func<Func<Context, Context>, Func<Context, Context>> middleware = next =>
     {
         Func<Context, Context> process = context =>
         {
             /*process request*/
           
             next(context);
             /*process response*/
             return  context;
         };
         return  process;
     };
     return  middleware;
}

这一过程是理解函数式方案的关键,所有Middleware可以聚合为一个Func<Context,Context>,为了易于阅读,我们可以定义一个委托:

1
public  delegate  Context RequestDelegate(Context context);

给定初始RequestDelegate,聚合所有Middleware:

1
2
3
4
5
6
7
8
9
10
11
1 13
public  IApplication Build()
{
     RequestDelegate request = context => context;
     _middlewares.Reverse();
     foreach  ( var  middleware in  _middlewares)
     {
         request = middleware(request);
     }
     return  new  Application(request);
}

自定义一个函数式Middleware:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1 8
19
20
21
22
public  class  DefaultMiddleware:IMiddleware
{
     public  Func<RequestDelegate, RequestDelegate> Request()
     {
         Func<RequestDelegate, RequestDelegate> request = next =>
         {
             return  context =>
             {
                 context.Request.Process( "default request" , "processed by defaultMiddleware" );
                 next(context);
                 context.Response.Process( "default response" , "processed by defaultMiddleware" );
                 return  context;
             };
         };
         return  request;
     }
}

所有代码提供下载:https://git.oschina.net/richieyangs/Pipeline.Middleware.git

相关文章

原文地址:http://www.cnblogs.com/richieyang/p/5315390.html


.NET社区新闻,深度好文,微信中搜索dotNET跨平台或扫描二维码关注


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/329827.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

怎么样安装Ubuntu系统,一文告诉你

前言 额滴神呐/(ㄒoㄒ)/~~&#xff0c;用惯了windows开发&#xff0c;初上手Linux桌面开发真的是举步维艰&#xff08;内心ps&#xff1a;谁让你立这个标题的&#xff0c;现在后悔了吧… 你自己想办法 怎么把这个标题栏目圆过去&#xff09; 经过跟内心戏反复的都在&#xff0…

(转) SpringBoot接入两套kafka集群

转自&#xff1a; SpringBoot接入两套kafka集群 - 风小雅 - 博客园引入依赖 compile org.springframework.kafka:spring-kafka 第一套kafka配置 package myapp.kafka; importhttps://www.cnblogs.com/ylty/p/13673357.html 引入依赖 compile org.springframework.kafka:spring…

idea tomcat部署web项目_项目开发之部署帆软到Tomcat服务一

书接上回上一篇文章介绍了两种图表取数的方式&#xff0c;新增数据库查询和通过存储过程取数&#xff0c;其他的内置数据集&#xff0c;文件数据集和关联数据集等方式暂时还没有用到&#xff0c;先暂时不介绍了&#xff0c;等之后用到了或者等小编有时间试过之后再来做个简单的…

C#工业物联网和集成系统解决方案的技术路线

前言 2000年以后&#xff0c;互联网在中国的大地上如火如荼的发展&#xff0c;在这个行业竞争中比的是加速度。我清晰的记得《世界是平的》中有这样一段话&#xff1a;在非洲&#xff0c;羚羊每天早上醒来时&#xff0c;它知道自己必须跑得比最快的狮子还快&#xff0c;否则就会…

转:Kafka事务使用和编程示例/实例

Kafka事务使用和编程示例/实例_JobShow裁员加班实况-微信小程序-CSDN博客一、概述​ Kafka事务特性是指一系列的生产者生产消息和消费者提交偏移量的操作在一个事务中&#xff0c;或者说是一个原子操作&#xff0c;生产消息和提交偏移量同时成功或者失败。注意&#xff1a;kafk…

[初级]Java中的switch对整型、字符型、字符串的具体实现细节

转载自 [初级]Java中的switch对整型、字符型、字符串的具体实现细节Java 7中&#xff0c;switch的参数可以是String类型了&#xff0c;这对我们来说是一个很方便的改进。到目前为止switch支持这样几种数据类型&#xff1a;byteshort int char String 。但是&#xff0c;作为一个…

SpringBoot-Cache整合redis

前言 SpringBoot的众多Starter有两个很重要的缓存Starter&#xff0c;其中一个是我们经常用到的Redis&#xff08;spring-boot-starter-data-redis&#xff09;还有一个是 spring-boot-starter-cache。 今天主要是简单介绍一个如何整合这两个组件&#xff0c;达到相互合作的关系…

C#跨平台物联网通讯框架ServerSuperIO(SSIO)

一.SSIO的特点 轻型高性能通信框架&#xff0c;适用于多种应用场&#xff0c;轮询模式、自控模式、并发模式和单例模式。设备驱动、IO通道、控制模式场景协调统一。设备驱动内轩命令驱动器、命令缓存器、自定义参数和实时数据元素。框架平台支持按设备命令优先级别进行调度&…

spring boot 单元测试_spring-boot-plus1.2.0-RELEASE发布-快速打包-极速部署-在线演示

spring-boot-plusspring-boot-plus集成spring boot常用开发组件的后台快速开发脚手架Purpose每个人都可以独立、快速、高效地开发项目&#xff01;Everyone can develop projects independently, quickly and efficiently&#xff01;官网地址&#xff1a;springboot.plusGITHU…

在Java中如何高效的判断数组中是否包含某个元素

转载自 在Java中如何高效的判断数组中是否包含某个元素如何检查一个数组(无序)是否包含一个特定的值&#xff1f;这是一个在Java中经常用到的并且非常有用的操作。同时&#xff0c;这个问题在Stack Overflow中也是一个非常热门的问题。在投票比较高的几个答案中给出了几种不同的…

spring-kafka整合:DefaultKafkaProducerFactory默认kafka生产者工厂介绍

【README】 0&#xff0c;为啥要看 DefaultKafkaProducerFactory&#xff1f; 最近在基于 springboot 开发kafka模块&#xff0c;发现 kafakTemplate构造器传入了 DefaultKafkaProducerFactory实例&#xff0c; kafkaTemplate内部使用了 很多 DefaultKafkaProducerFactory的方…

【SpringSecurity】【JJWT】JJWT踩坑LocalDateTime

前言 最近自己又在开始闲搞&#xff0c;主要原因还是下山无望&#xff08;买显卡&#xff09;。只能晚上下班找点事情做啦~~ 环境 版本请根据实际情况参考JJWT官网选择使用&#xff0c;这里只说明一下问题大概思路&#xff01; <!-- 增加token生成依赖 --> <depen…

针对Linux ASP.NET MVC网站中 httpHandlers配置无效的解决方案

近期有Linux ASP.NET用户反映&#xff0c;在MVC网站的Web.config中添加 httpHandlers 配置用于处理自定义类型&#xff0c;但是在运行中并没有产生预期的效果&#xff0c;服务器返回了404&#xff08;找不到网页&#xff09;错误。经我亲自测试&#xff0c;在WebForm网站中&…

简单介绍Java中Comparable和Comparator

转载自 简单介绍Java中Comparable和ComparatorComparable 和 Comparator是Java核心API提供的两个接口&#xff0c;从它们的名字中&#xff0c;我们大致可以猜到它们用来做对象之间的比较的。但它们到底怎么用&#xff0c;它们之间有又哪些差别呢&#xff1f;下面有两个例子可以…

spring-kafka整合:KafkaTemplate-kafka模板类介绍

【README】 1&#xff0c;本文主要关注 KafkaTemplate的重点方法&#xff0c;并非全部方法&#xff1b; 2&#xff0c;KafkaTemplate 底层依赖于 DefaultKafkaProducerFactory &#xff0c; 关于 DefaultKafkaProducerFactory 的介绍&#xff0c;refer2 spring-kafka整合:…

安卓 on a null object reference_详解Object.prototype.__proto__

Object.prototype 的 __proto__ 属性是一个访问器属性(一个getter函数和一个setter函数), 暴露了通过它访问的对象的内部[[Prototype]] (一个对象或 null)。使用__proto__是有争议的&#xff0c;也不鼓励使用它。因为它从来没有被包括在EcmaScript语言规范中&#xff0c;但是现…

【SpringBoot】服务器JVM远程调试

目的 当系统部署到测试环境服务器时&#xff0c;难免会遇到bug。这个时候如果能远程调试&#xff0c;那么能够大大提高我们的生产效率&#xff0c;快速完成服务调试&#xff0c;最快发布生产环境。&#xff08;领导好评不就到手了&#xff09; 准备 Idea&#xff08;Java最好…

图说:为什么Java中的字符串被定义为不可变的

转载自 图说&#xff1a;为什么Java中的字符串被定义为不可变的字符串&#xff0c;想必大家最熟悉不过了&#xff0c;通常我们在代码中有几种方式可以创建字符串&#xff0c;比如&#xff1a;String s "Hollis";这时&#xff0c;其实会在堆内存中创建一个字符串对象…

值得推荐的微软技术公众号推荐

为开阔技术人眼界&#xff0c;促进技术人职业成长。小二在此诚意推荐最值得关注的微软技术公众号。平时关注推送的文章或多或少要么学到知识技能&#xff0c;要么收到一些启发&#xff0c;有利于个人成长。这些公众号为笔者个人积累&#xff0c;不一定都合大家口味&#xff0c;…

springboot:BeanPostProcessor示例及分析

【README】 1&#xff0c;本文主要分析 BeanPostProcessor 的作用&#xff0c; 开发方式&#xff1b; 2&#xff0c;BeanPostProcessor 是bean后置处理器&#xff0c; 简而言之就是bean被创建好了&#xff0c;之后如果需要对其属性进行修改&#xff0c;则 需要使用 BeanPost…