为单元测试等非WebBase的项目伪造一个HttpContext , Session 和HttpHeader

在做单元测试的时候HttpContext.Current是为null的

而有些dll是和HttpContext绑定的(很大原因是...net大部分用于web项目)

或者是试图在windows form 或者console中使用这些dll就挂了...

当然HttpContext.Current是可以赋值的...那么最最简单的方法就是直接new一个HttpContext给它啦

HttpRequest request = new HttpRequest("", "http://localhost", "");
HttpContext.Current
= new HttpContext(request, new HttpResponse(new System.IO.StringWriter()));

好吧 如果需要Session的话还需要添加下面的代码

System.Web.SessionState.SessionStateUtility.AddHttpSessionStateToContext(
HttpContext.Current,
new HttpSessionStateContainer
(
"",
new SessionStateItemCollection(),
new HttpStaticObjectsCollection(),
20000,
true,
HttpCookieMode.UseCookies,
SessionStateMode.Off,
false
)
);

问题又出现了......有的代码会读取HttpHeader...例如ip什么的经常就存储在这里

更郁闷的是HttpContext的类经常是不能设置HttpHeader的.....

因为这个是只读的.......

其实只读这东西在.net中基本是骗人的.也就编译时有点用

到运行时 别说只读了 连private 都可以通过反射弄出来

那么就用反射赋值给httpheader吧

var instance = HttpContext.Current.Request.ServerVariables;
Type type
= instance.GetType();
BindingFlags temp
= BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;

MethodInfo addStatic
= null;
MethodInfo makeReadOnly
= null;
MethodInfo makeReadWrite
= null;


MethodInfo[] methods
= type.GetMethods(temp);
foreach (MethodInfo method in methods)
{
switch (method.Name)
{
case "MakeReadWrite": makeReadWrite = method;
break;
case "MakeReadOnly": makeReadOnly = method;
break;
case "AddStatic": addStatic = method;
break;
}
}

makeReadWrite.Invoke(instance,
null);
List
<string[]> list = new List<string[]>();
string ip = ServiceContext.IPAddress;
list.Add(
new string[] { "HTTP_X_FORWARDED_FOR", ip });
list.Add(
new string[] { "HTTP_CLIENT_IP", ip });
list.Add(
new string[] { "HTTP_X_FORWARDED", ip });
list.Add(
new string[] { "HTTP_X_CLUSTER_CLIENT_IP", ip });
list.Add(
new string[] { "HTTP_FORWARDED_FOR", ip });
list.Add(
new string[] { "HTTP_FORWARDED", ip });
list.Add(
new string[] { "REMOTE_ADDR", ip });
foreach (string[] values in list)
addStatic.Invoke(instance, values);
makeReadOnly.Invoke(instance,
null);

posted on 2011-03-31 18:15  听说读写  阅读(1881)  评论(1编辑  收藏  举报

导航