// reflect to readonly property
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
// make collection editable
isreadonly.SetValue(this.Request.QueryString, false, null);
// make collection readonly again
isreadonly.SetValue(this.Request.QueryString, true, null);
@Skuli - You're modifying something which isn't intended for modification, and you're doing that by changing a state flag. There's some risk that you might do something destructive if you forget to "close" the reflection change, but it's pretty low and would require a developer to be pretty unaware of what the code is doing. Request here is scoped through IHttpHandler, so any old System.Web.Page can do this.
Great stuff. Is this not dangerous at all? What is the scope of this.Request.QueryString in this context?
I am using this in a case where I have a UserControl I can't modify that uses a query string parameter, and the only way to change the way that UserControl behaves is to change the query string before it processes it (I also can't change the actual incoming URL, I have to modify it during the the load cycle.) Very helpful, and it works great.
My personal preference here is rewriting the query or working with a namevaluecollection at a lower point, but there are times where the business logic makes neither of those very helpful and sometimes reflection really is what you need. In those circumstances you can just turn off the readonly flag for a moment like so: