Change Request.Form collection on the fly

How to modify Request.Form collection

  • Share

Data from form are sent to backend (whether code behing of page in WebForms or Controller Action in MVC) in Request.Form property.

It is oragnized as collection of name and value and can be easily access by name. In some extreme cases, you need to make some modifications to posted form data.

This can be done with reflection but there is a small catch. Request.Form property is ReadOnly. Than means that Set method is not declared on this property.

If you try to set it directly you will get an exception

var collection = System.Web.HttpContext.Current.Request.Form;
            collection.Add("email", "mymail@domain.com");
    

Readonlyexc

What we need to do now is to unlock Form collection for adding new items. This is done by setting IsReadOnly property with reflection.

var collection = System.Web.HttpContext.Current.Request.Form;
            var propInfo = collection.GetType().GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
            propInfo.SetValue(collection, false, new object[] { });
            collection.Add("email", "mymail@domain.com");
    

This will remove read-only protection from the Form property of the Request and you can do your changes on the Form collection object of the current request.

  • Share

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

Comments for this article

comments powered by Disqus