有没有办法设置HttpResponse?

时间:2011-02-01 08:37:20

标签: c# asp.net unit-testing httprequest httpresponse

我有以下代码用于设置HttpRequest查询字符串。我想对Request.Form做同样的事情。

我这样做是为了一起攻击一些单元测试。我想对Request.Form做同样的事情,我不认为我有兴趣在这一点上嘲笑,寻找黑客。

现有的Querystring hack ....

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 个答案:

答案 0 :(得分: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 :(得分:1)

您可以使用Reflection调用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" } }
            });
}