Change Request.Form collection on the fly

How to modify Request.Form collection

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.

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.


About the author

DEJAN STOJANOVIC

Dejan Stojanovic is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform includion ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article