c# - 模拟的 HttpRequest 丢失了 QueryString

标签 c# asp.net unit-testing mocking httprequest

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

我使用这个辅助方法来模拟 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/

相关文章:

javascript - 如何使用 AJAX 正确调用 MVC Controller

asp.net - Azure SQL 数据库 v12 - 全文查询

c# - 定时器每周抛出一次方法 - C#、Asp.NET

unit-testing - 如何设置对特定类型的 Equals 调用覆盖 MoQ 中的 Equals?

c# - C++/命令行界面 : preventing garbage collection on managed wrapper of unmanaged resource

c# - 报告框架背后的基本原理

c# - 从不可搜索的流中打开 System.IO.Packaging.Package

asp.net - 有谁知道 Razor、Spark 和 NVelocity View 引擎之间的性能差异?

c# - 如何在 asp.net mvc 中模拟基本 Controller ?

javascript - 如何在 Jasmine 中测试 Sequelize?