Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I modify Request.Form variables?

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

Collection is read-only

like image 886
complez Avatar asked Nov 27 '08 08:11

complez


2 Answers

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

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

like image 130
annakata Avatar answered Sep 28 '22 18:09

annakata


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).

like image 20
Marc Gravell Avatar answered Sep 28 '22 16:09

Marc Gravell