我发现此代码用于执行模拟请求以进行单元测试。我正在尝试设置用户主机地址,但我不清楚如何使用此代码中概述的相同方法来实现这一点。我认为它必须通过反射来完成,因为我发现不允许设置标题。有什么想法可以实现这一目标吗?
public static HttpContext FakeHttpContext()
{
var httpRequest = new HttpRequest("", "http://fakurl/", "");
var stringWriter = new StringWriter();
var httpResponse = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponse);
var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
new HttpStaticObjectsCollection(), 10, true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc, false);
httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null, CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null)
.Invoke(new object[] { sessionContainer });
httpContext.Request.Headers["REMOTE_ADDR"] = "XXX.XXX.XXX.XXX"; // not allowed
return httpContext;
}
我也试过这个模拟库:
https://gist.github.com/rally25rs/1578697
由用户主机地址仍然是只读的。