33

I have a QueryString named 'flagEdit' and I want to remove it after fetching it's value. But when i try to remove it using

Request.QueryString.Clear();

or

Request.QueryString.Remove("editFlag");

This error occurs -

System.NotSupportedException: Collection is read-only.

So, I want to know how to remove query string after fetches it's value

ulluoink
  • 2,775
  • 2
  • 17
  • 22
Piyush
  • 542
  • 1
  • 8
  • 17
  • 4
    You can't, because that's the way your page was called. The only way to 'clear' the query string is to do a redirect to the same URL but without the query string part. – Mark Jan 22 '14 at 10:22
  • You can look at a similar approach [here](http://stackoverflow.com/questions/51964/how-do-i-remove-items-from-the-query-string-for-redirection) – Pinte Dani Jan 22 '14 at 10:25
  • 2
    Is there particular reason why you want it cleared? If security is the issue, try using a POST call instead or encrypt the query string. – BWHazel Jan 22 '14 at 10:59
  • 2
    http://stackoverflow.com/questions/4968731/why-is-request-querystring-readonly – Nagaraj S Jan 22 '14 at 11:37
  • I saw the answer here and it works for me. http://www.dotnetfunda.com/forums/show/12918/how-to-clear-the-querystring-values-after-retrieving – khazan Feb 05 '18 at 04:56

4 Answers4

51

Removing (Deleting) Querystring in ASP.NET

Request.QueryString.Remove("editFlag")

If you do the above, you will get an error

collection is read-only.

So, we need to write the below code before deleting the query string.

Try this way

PropertyInfo isreadonly = 
  typeof(System.Collections.Specialized.NameValueCollection).GetProperty(
  "IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
// make collection editable
isreadonly.SetValue(this.Request.QueryString, false, null);
// remove
this.Request.QueryString.Remove("editFlag");

You can also try this way

    var nvc = HttpUtility.ParseQueryString(Request.Url.Query);
    nvc.Remove("editFlag");
    string url = Request.Url.AbsolutePath + "?" + nvc.ToString();
     Response.Redirect(url);

Hope this helps

Community
  • 1
  • 1
Amarnath Balasubramanian
  • 9,300
  • 8
  • 34
  • 62
  • 4
    That's a good answer to his question, but I think the question deserves attention. What would you want to do that for in the first place? The reality is that the page was called with the querystring intact; you can't change that fact, whether you like the parameters or not. Cheating the undesired parameter away doesn't change that fact either. So a ReadOnlyCollection makes perfect sense IMHO. Would it not be better to have smarter code that just ignores the parameter? – increddibelly Oct 16 '15 at 11:28
  • 2
    Because you might just need to update a value in the query string. Sometimes, especially in the case with inherited code, you need to do unconventional things in order not to break existing code. – user4593252 Jun 10 '16 at 19:26
  • Worked for the VB.NET version of the code at https://www.codeproject.com/Tips/177679/Removing-Deleting-Querystring-in-ASP-NET – DJDave Nov 17 '17 at 14:07
  • Curious to know why so many people want to do this. I guess they tried it so understand that it wont actually remove the parameter from the URL. Obviously as mentioned above there can be the occasional odd case with legacy code where you have to do something out of the ordinary but I guess with this many up-votes there must be a fairly common case for this, but if it was known what the case was there could obviously be more suitable approaches. If I saw this in my teams production code I would be seriously questioning their judgement – rdans Sep 21 '20 at 11:09
14

If you are concerned about future page postbacks running the same code you intended to run when querystring has a value, simply add a if(!Page.IsPostBack) condition.

SanthoshM
  • 481
  • 4
  • 5
9

If you want to clear the entire QueryString, this worked for me:

Response.Redirect(Request.RawUrl.Replace(Request.Url.Query, ""));

I was clearing a form which had some fields auto-populated by the QueryString, thus wanting to whack the whole thing.

However, the other guys' answers are probably better if you are targeting a specific parameter and want to leave the rest.

gregtheross
  • 385
  • 4
  • 9
1

I have taken the liberty in @Amarnath Balasubramanian 's answer above, and made it a handy function that can be easily called in VB.NET too.

public static bool RemoveQueryString(ref System.Web.HttpRequest httpReq, string key)
{
    PropertyInfo requestQueryString = null;
    bool bCanProceed = true;
    try {
        try {
            requestQueryString = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
        } catch (System.Reflection.AmbiguousMatchException) {
            bCanProceed = false;
        } catch (System.ArgumentNullException) {
            bCanProceed = false;
        }
        if (bCanProceed) {
            try {
                if (requestQueryString != null) {
                    // make collection editable
                    requestQueryString.SetValue(httpReq.QueryString, false, null);
                } else bCanProceed = false;

            } catch (System.Reflection.TargetException) {
                bCanProceed = false;
            } catch (System.Reflection.TargetParameterCountException) {
                bCanProceed = false;
            } catch (System.Reflection.TargetInvocationException) {
                bCanProceed = false;
            } catch (System.MethodAccessException) {
                bCanProceed = false;
            } catch (System.ArgumentException) {
                bCanProceed = false;
            }
            if (bCanProceed) {
                try {
                    // remove
                    httpReq.QueryString.Remove(key);
                } catch (System.NotSupportedException) {
                    bCanProceed = false;
                }
            }
        }
    } catch (System.Exception) {
        bCanProceed = false;
    }
    return bCanProceed;
}

To call this from VB.NET:

RemoveQueryString(Me.Request, "some_query_key_here")
t0mm13b
  • 34,087
  • 8
  • 78
  • 110
  • Some irritable user downvoting both this and the poster's accepted answer! – t0mm13b Mar 31 '15 at 17:03
  • 6
    Wow! I've never seen so much code to handle exceptions! 3 useful lines of code and nearly 40 to handle exceptions (some of which cannot even be thrown). – NickG Apr 17 '15 at 10:26
  • I like using a method. I however, would not write it this way. I would instead pull off GetProperties() and make the best decision on my own, instead of relying on error trapping. Then have 1 try catch just in case. IMO, you should work on your technique. Good thoughts, and good beginner code, but most of it unnecessary. – Jimmie Clark Jun 14 '16 at 19:43