我需要測試一個管理複雜查詢字符串的助手類。Mocked HttpRequest丟失QueryString
我用這個輔助方法來嘲笑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","");
我不知道有足夠的瞭解這一點,但我並複製你的代碼並運行它。你說querystring沒有出現在url中,但是它並沒有完全從'HttpContext'中去掉,因爲'QueryString'屬性仍然有它。我不知道預期的行爲是什麼。 – Halvard
@Halvard謝謝,您的評論已將我指向解決方案! – giammin