2013-10-31 22 views
2

我需要測試一個管理複雜查詢字符串的助手類。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",""); 
+2

我不知道有足夠的瞭解這一點,但我並複製你的代碼並運行它。你說querystring沒有出現在url中,但是它並沒有完全從'HttpContext'中去掉,因爲'QueryString'屬性仍然有它。我不知道預期的行爲是什麼。 – Halvard

+0

@Halvard謝謝,您的評論已將我指向解決方案! – giammin

回答

2

感謝Halvard's comment我有線索找到答案:

HttpRequest constructor parameters在它們之間斷開。

url參數是用來創建HttpRequest.Url和查詢字符串用於HttpRequest.QueryString屬性:它們分離

有一致的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; 
} 
0

試試這個:

Uri uriFull = new Uri(HttpContext.Current.Request.Url, HttpContext.Current.Request.RawUrl); 
+0

我需要模擬httpContext! – giammin