我需要向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
收藏?
编辑:
当我尝试这种方法时,我得到了一个异常(对象引用未设置为对象的实例。):
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);
答案 0 :(得分: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);
}
}
您可能需要更改编码类型,但希望这可以帮助您,除非我的问题完全错误。