In my base page I need to remove an item from the query string and redirect. I can't use
Request.QueryString.Remove("foo")
because the collection is read-only. Is there any way to get the query string (except for that one item) without iterating through the collection and re-building it?
You can avoid touching the original query string by working on a copy of it instead. You can then redirect the page to the a url containing your modified query string like so:
var nvc = new NameValueCollection();
nvc.Add(HttpUtility.ParseQueryString(Request.Url.Query));
nvc.Remove("foo");
string url = Request.Url.AbsolutePath;
for (int i = 0; i < nvc.Count; i++)
url += string.Format("{0}{1}={2}", (i == 0 ? "?" : "&"), nvc.Keys[i], nvc[i]);
Response.Redirect(url);
Update:
Turns out we can simplify the code like so:
var nvc = HttpUtility.ParseQueryString(Request.Url.Query);
nvc.Remove("foo");
string url = Request.Url.AbsolutePath + "?" + nvc.ToString();
Response.Redirect(url);
You'd have to reconstruct the url and then redirect. Something like this:
string url = Request.RawUrl;
NameValueCollection params = Request.QueryString;
for (int i=0; i<params.Count; i++)
{
if (params[i].GetKey(i).ToLower() == "foo")
{
url += string.Concat((i==0 ? "?" : "&"), params[i].GetKey(i), "=", params.Get(i));
}
}
Response.Redirect(url);
Anyway, I didn't test that or anything, but it should work (or at least get you in thye right direction)
Response.Redirect(String.Format("nextpage.aspx?{0}", Request.QueryString.ToString().Replace("foo", "mangledfoo")));
I quick hack, saves you little. But foo will not be present for the code awaiting it in nextpge.aspx :)
Interesting question. I don't see any real viable alternative to manually copying the collection since CopyTo will only allow you to get the values (and not the keys).
I think HollyStyles' Hack would work (although I would be nervous about putting a Replace in a QueryString - obv. dependant on use case), but there is one thing thats bothering me..
If the target page is not reading it, why do you need to remove it from the QueryString?
It will just be ignored?
Failing that, I think you would just need to bite the bullet and create a util method to alter the collection for you.
Ahhhh! I see now, yes, I have had similar problems with SiteMap performing full comparison of the string.
Since changing the other source code (i.e. the search) is out of the question, I would probably say it may be best to do a Replace on the string. Although to be fair, if you often encounter code similar to this, it would equally be just as quick to set up a utility function to clone the collection, taking an array of values to filter from it.
This way you would never have to worry about such issues again :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With