2

我需要向 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.FormCollection 中吗?

编辑:

当我尝试这种方法时,我遇到了一个异常(对象引用未设置为对象的实例。):

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);
4

1 回答 1

0

在将数据添加到帖子之前建立您的数据。

您需要将数据添加到请求的流中,这样应该可以:

using(HttpWebRequest myHttpRequest = (HttpWebRequest)WebRequest.Create(myUrl)
{
   byte[] bytes = Encoding.UTF8.GetBytes(myFormData);
   Stream requestStream = null;
   try
   {
      myHttpRequest.ContentLength = bytes.Length;
      requestStream = myHttpRequest.GetRequestStream();
      requestStream.Write(bytes, 0, bytes.Length);
   }
}

您可能需要更改编码类型,但希望这可以帮助您,除非我完全弄错了您的问题。

于 2012-11-20T09:36:44.500 回答