How do I remove items from the query string for re

2019-06-16 19:22发布

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?

10条回答
【Aperson】
2楼-- · 2019-06-16 19:28

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)

查看更多
Viruses.
3楼-- · 2019-06-16 19:28
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 :)

查看更多
不美不萌又怎样
4楼-- · 2019-06-16 19:29

Can you clone the collection and then redirect to the page with the cloned (and modified) collection?

I know it's not much better than iterating...

查看更多
再贱就再见
5楼-- · 2019-06-16 19:34

I found this was a more elegant solution

var qs = HttpUtility.ParseQueryString(Request.QueryString.ToString());
qs.Remove("item");
Console.WriteLine(qs.ToString());
查看更多
一纸荒年 Trace。
6楼-- · 2019-06-16 19:39

HttpUtility.ParseQueryString(Request.Url.Query) return isQueryStringValueCollection. It is inherit from NameValueCollection.

    var qs = HttpUtility.ParseQueryString(Request.Url.Query);
    qs.Remove("foo"); 

    string url = "~/Default.aspx"; 
    if (qs.Count > 0)
       url = url + "?" + qs.ToString();

    Response.Redirect(url); 
查看更多
别忘想泡老子
7楼-- · 2019-06-16 19:43

Request.Url.GetLeftPart(UriPartial.Path) should do this

查看更多
登录 后发表回答