我需要向 Request.Form 集合添加值,但我不明白如何HttpRequest
使用指定的表单值初始化实例。我试图覆盖Initialize
控制器中的方法并像这样初始化HttpRequest
:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
var requestField = typeof (HttpRequestWrapper).GetField("_httpRequest", BindingFlags.NonPublic |
BindingFlags.Instance);
var responseField = typeof(HttpResponseWrapper).GetField("_httpResponse", BindingFlags.NonPublic | BindingFlags.Instance);
var req = (HttpRequest) requestField.GetValue(requestContext.HttpContext.Request);
var res = (HttpResponse)responseField.GetValue(requestContext.HttpContext.Response);
//**************** HERE I TRY TO INITIZLIZE FORM COLLECTION WITH MY VALUE 'additional_form_value' but nothing
var newReq = new HttpRequest(null, req.Url.ToString(), "?additional_form_value=test");
newReq.RequestType = "POST";
//***************
var r = new RequestContext(new HttpContextWrapper(new HttpContext(newReq, res)), requestContext.RouteData);
base.Initialize(r);
}
有什么方法可以将新项目添加到Request.Form
Collection 中吗?
编辑:
当我尝试这种方法时,我遇到了一个异常(对象引用未设置为对象的实例。):
NameValueCollection oQuery = requestContext.HttpContext.Request.QueryString;
oQuery = (NameValueCollection)requestContext.HttpContext.Request.GetType().GetField("_form", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(requestContext.HttpContext.Request); //exception here
PropertyInfo oReadable = oQuery.GetType().GetProperty("IsReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
oReadable.SetValue(oQuery, false, null);
oQuery["foo"] = "bar";
oReadable.SetValue(oQuery, true, null);