Search code examples
asp.netc#-4.0asp.net-4.0

change query string values without redirect in c#


I have a query string that looks something like this:

"somename1=123&QueryString=PlaceHolder%3dNothing%26anotherid%3dsomevalue&somename=somevalue"

but I want the query string to be something like the query string below and replace the whole query string with the updated one is there any way to do that without redirection?

"somename1=somevalue1&PlaceHolder=Nothing&somename2=somevalue2&somename3=somevalue3"

basically need to remove: "QueryString=" with empty string "%3d" with "&" "%26" with "="

So far I've done is:

string strQueryString = Request.QueryString.ToString();
if (strQueryString.Contains("QueryString="))
{
    strQueryString = strQueryString.Replace("QueryString=", "");
    if (strQueryString.Contains("%26")) strQueryString = strQueryString.Replace("%26", "&");
    if (strQueryString.Contains("%3d")) strQueryString = strQueryString.Replace("%3d", "=");
    string x = strQueryString;
}

and:

 // 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);
if (this.Request.QueryString.ToString().Contains("QueryString="))
{
    this.Request.QueryString.ToString().Replace("QueryString=", "");
    if (this.Request.QueryString.ToString().Contains("%26")) this.Request.QueryString.ToString().Replace("%26", "&");
    if (this.Request.QueryString.ToString().Contains("%3d")) this.Request.QueryString.ToString().Replace("%3d", "=");
    string x = this.Request.QueryString.ToString();
}

// make collection readonly again
isreadonly.SetValue(this.Request.QueryString, true, null);

The second part of the code is not replacing the characters and I don't know how after removing all character or replacing them change the query string to new query string.

Any help is greatly appreciated.


Solution

  • Changing the query string of the current request is not supported. Using private Reflection to edit some in-memory state will most likely break ASP.NET because it assumes that the query string is immutable. The only way to change the query string is to issue a new request, either by doing a redirect, or by doing a sort of sub-request, such as by making a new HTTP request to the same page but with a different query string.