我可以修改Request.Form变量吗? [英] Can I modify Request.Form variables?

查看:215
本文介绍了我可以修改Request.Form变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试Request.Form.Set(k, v),但是它引发了异常

I try Request.Form.Set(k, v) but it's throwing exception

集合为只读

Collection is read-only

推荐答案

这与修改Request.Querystring完全相同.两者在内部都因私有财产而复杂,并且可能被认为是错误,但是我知道有两种可能的解决方案(我会不理会response.redirect计划-这很糟糕).

This is exactly the same as modifying Request.Querystring. Both are internally complicated by private properties and what could be deemed a bug, however there are two possible solutions I'm aware of (I'll dismiss the response.redirect plan out of hand - that's terrible).

方法之一是使用反射直接修改集合:

Method one is to use reflection to modify the collection directly:

NameValueCollection oQuery = Request.QueryString;
oQuery = (NameValueCollection)Request.GetType().GetField("_queryString",BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Request);
PropertyInfo oReadable = oQuery .GetType().GetProperty("IsReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
oReadable.SetValue(oQuery, false, null);
oQuery["foo"] = "bar";
oReadable.SetValue(oQuery, true, null); 

我认为更适合单元测试的

B计划是避免直接处理集合,而应将它作为NameValueCollection传递给要处理的任何方法,并从其中随意复制任何内容.我本人已使用它来模拟Web请求.

Plan B, which I think lends itself better to unit testing is to avoid dealing with the collection directly and instead pass it as a NameValueCollection to any method you want to handle it, shallow copying whatever you need out of it. I've used this myself to mock web requests.

马克·格雷韦尔(Marc Gravell)提出了雄辩的计划B理由

Marc Gravell gave more eloquent reasons for plan B

这篇关于我可以修改Request.Form变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆