2011-02-01 119 views
1

我有以下代碼,我用它來設置HttpRequest查詢字符串。我想爲Request.Form做同樣的事情。有沒有辦法設置HttpResponse?

我這樣做是爲了破解一些單元測試。我想爲Request.Form做同樣的事情,我不認爲我有興趣嘲笑這一點,尋找黑客。

現有的查詢字符串劈....

private string _queryString; 
public string QueryString 
{ 
    get { return _queryString; } 
    set 
    { 
     _queryString = value; 
     HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", value), new HttpResponse(null)); 
    } 
} 

我怎樣才能做到在設定的Request.Form類型值(帶保留查詢字符串過的選項)一樣嗎?

回答

2

此帖包含了答案 - stackoverflow: Can I change the value of a POST value without re-POSTing?

protected void SetFormValue(string key, string value) 
{ 
    var collection = HttpContext.Current.Request.Form; 

    // Get the "IsReadOnly" protected instance property. 
    var propInfo = collection.GetType().GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic); 

    // Mark the collection as NOT "IsReadOnly" 
    propInfo.SetValue(collection, false, new object[] { }); 

    // Change the value of the key. 
    collection[key] = value; 

    // Mark the collection back as "IsReadOnly" 
    propInfo.SetValue(collection, true, new object[] { }); 
} 
1

您可以使用反射調用internal SwitchForm(NameValueCollection)和它包裝成一個擴展方法:

public static void SetForm(this HttpRequest request, NameValueCollection collection) 
{ 
    typeof(HttpRequest).GetMethod(
     "SwitchForm", 
     BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod 
     ).Invoke(
      request ?? HttpContext.Current.Request, 
      new[] 
      { 
       collection ?? new NameValueCollection { { "name", "value" } } 
      }); 
} 
+0

,看起來很不錯,但我得到一個錯誤:System.ArgumentException:類型'System.Collections.Specialized.NameValueCollection'的對象無法轉換爲類型'System.Web.HttpValueCollection' – 2011-02-01 22:16:16

相關問題