ASP.NET Core 1.0中的管道-中间件模式
作者:网络转载 发布时间:[ 2016/6/12 14:06:37 ] 推荐标签:ASP.NET 测试开发技术
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
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11