我可以修改 Request.Form 变量吗?
我尝试 Request.Form.Set(k, v)
但它抛出异常
集合是只读的
I try Request.Form.Set(k, v)
but it's throwing exception
Collection is read-only
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这与修改
Request.Querystring
完全相同。 两者都因私有属性而内部复杂化,并且可能被视为错误,但是我知道有两种可能的解决方案(我将立即驳回 response.redirect 计划 - 这太糟糕了)。方法一是使用反射直接修改集合:
B 计划,我认为更适合单元测试的是避免直接处理集合,而是将其作为
NameValueCollection
传递给您的任何方法想要处理它,浅层复制你需要的任何东西。 我自己用它来模拟网络请求。编辑:Marc Gravell 为 B 计划给出了更雄辩的理由
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:
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.Edit: Marc Gravell gave more eloquent reasons for plan B
该表单表示客户端在请求中发送的内容。 你想做什么? 就我个人而言,我会尝试将“读取表单”代码与“对值执行某些操作”代码分开 - 这样,您可以尽早(从表单读取时)进行任何预处理,而以后则不会进行任何预处理代码需要知道实际发送的内容 - 它只接受给定的值(即它从不直接与请求对话)。
这也意味着您可以测试您的逻辑,而无需表单,甚至根本不需要 http 请求。
实际上,ASP.NET MVC 会为您做很多这样的事情(上面的段落)...
请注意,您可以更新 .Items 集合 - 但这有点模糊(即它与表单没有具体关系) )。
The form is a representation of what the client sent in the request. What is it you want to do? Personally, I would try to separate the "read the form" code from the "do something with the values" code - that way, you can do any pre-processing early on (when reading from the form), and none of the later code needs to know about what was actually sent - it just takes the values given to it (i.e. it never talks to the request directly).
It also means you can test your logic without the need for a form, or even an http-request at all.
Actually, ASP.NET MVC will do a lot of this (the above paragraph) for you...
Note that you can update the .Items collection - but this is a bit more vague (i.e. it doesn't relate specifically to the form).