2

我需要测试一个管理复杂查询字符串的助手类。

我使用这个辅助方法来模拟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","");
4

2 回答 2

2

感谢Halvard 的评论,我有了找到答案的线索:

HttpRequest 构造函数参数在它们之间是断开的。

url 参数用于创建HttpRequest.Url,queryString 用于HttpRequest.QueryString属性:它们是分离的

要使 HttpRequest 与带有查询字符串的 url 一致,您必须:

var httpRequest = new HttpRequest
      ("", "http://www.google.com/?name=gdfgd", "name=gdfgd");

否则,您将无法正确加载 Url 或 QueryString 属性。

有我更新的 Mock Helpers 方法:

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;
}
于 2013-10-31T13:58:54.293 回答
0

尝试这个:

Uri uriFull = new Uri(HttpContext.Current.Request.Url, HttpContext.Current.Request.RawUrl);
于 2013-10-31T12:58:10.943 回答