我需要测试一个管理复杂查询字符串的帮助程序类。
我使用这个辅助方法来模拟 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","");
最佳答案
感谢Halvard's comment我有线索找到答案:
HttpRequest constructor parameters他们之间是断开的。
url 参数用于创建 HttpRequest.Url
,queryString 用于 HttpRequest.QueryString
属性:它们是分离的
要使 HttpRequest 与带有查询字符串的 url 保持一致,您必须:
var httpRequest = new HttpRequest
("", "http://www.google.com/?name=gdfgd", "name=gdfgd");
否则,Url 或 QueryString 属性将无法正确加载。
这是我更新的模拟助手方法:
public static HttpContext FakeHttpContext(string url)
{
var uri = new Uri(url);
var httpRequest = new HttpRequest(string.Empty, uri.ToString(), uri.Query.TrimStart('?'));
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;
}
关于c# - 模拟的 HttpRequest 丢失了 QueryString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19704059/