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

我使用此辅助方法来模拟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构造函数之后,查询字符串丢失了。

我正在使用的解决方法是将带有querystring的URL传递给HttpRequest构造函数:

HttpContext.Current = MockHelpers.FakeHttpContext("http://www.google.com/?name=gdfgd","");

最佳答案

感谢Halvard's comment,我有了找到答案的线索:

HttpRequest constructor parameters在它们之间断开连接。

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

要具有带有querystring的URL的一致HttpRequest,您必须:

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/

10-10 14:04