我需要测试一个管理复杂查询字符串的助手类。
我使用这个辅助方法来模拟HttpContext
:
public static HttpContext FakeHttpContext(string url, string queryString)
{
var httpRequest = new HttpRequest("", url, queryString);
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);
SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);
return httpContext;
}
问题是HttpRequest
丢失了查询字符串:
HttpContext.Current = MockHelpers.FakeHttpContext("http://www.google.com/", "name=gdfgd");
HttpContext.Current.Request.Url
是"http://www.google.com/"
而不是"http://www.google.com/?name=gdfgd"
像预期的那样。
如果我调试,我发现在 HttpRequest 构造函数之后,查询字符串就丢失了。
我正在使用的解决方法是将带有查询字符串的 url 传递给 HttpRequest 构造函数:
HttpContext.Current = MockHelpers.FakeHttpContext("http://www.google.com/?name=gdfgd","");