Run()方法将依次枚举Middleware并对消息的请求和响应进行处理,后返回终处理过的消息。
  接下来需要实现一个Middleware:
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注册进管道,我们还可以写一个扩展方法增加代码的可读性:
public static void UseDefaultMiddleware(this IApplicationBuilder applicationBuilder)
{
applicationBuilder.Use();
}
public static void Use(this IApplicationBuilder applicationBuilder)
where TMiddleware:IMiddleware
{
var middleware = applicationBuilder.Container.Resolve();
applicationBuilder.Use(middleware);
}
  写个测试看看吧:

  写第二个Middleware:
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来表示,再来看看这张图:

  一个Middleware的逻辑可以用Func, Func>来表示,整个Middleware的逻辑可以用下面的代码描述:
public Func, Func> Process()
{
Func, Func> middleware = next =>
{
Func process = context =>
{
/*process request*/
next(context);
/*process response*/
return context;
};
return process;
};
return middleware;
}
  这一过程是理解函数式方案的关键,所有Middleware可以聚合为一个Func,为了易于阅读,我们可以定义一个委托:
  public delegate Context RequestDelegate(Context context);
  给定初始RequestDelegate,聚合所有Middleware:
  public IApplication Build()
  {
  RequestDelegate request = context => context;
  _middlewares.Reverse();
  foreach (var middleware in _middlewares)
  {
  request = middleware(request);
  }
  return new Application(request);
  }
  自定义一个函数式Middleware:
public class DefaultMiddleware:IMiddleware
{
public Func Request()
{
Func 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