C# 如何从查询字符串中删除项目以进行重定向?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I remove items from the query string for redirection?
提问by Danimal
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?
因为集合是只读的。有没有办法在不遍历集合并重新构建它的情况下获取查询字符串(除了那一项)?
采纳答案by Ryan Farley
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)
无论如何,我没有测试那个或任何东西,但它应该工作(或者至少让你朝着正确的方向前进)
回答by hollystyles
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 :)
我快速破解,为您节省一点。但是 foo 不会出现在 nextpge.aspx 中等待它的代码:)
回答by Michael Haren
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...
我知道这并不比迭代好多少...
回答by Rob Cooper
Interesting question. I don't see any real viable alternative to manually copying the collection since CopyTowill only allow you to get the values (and not the keys).
有趣的问题。我没有看到手动复制集合的任何真正可行的替代方法,因为CopyTo只允许您获取值(而不是键)。
I think HollyStyles' Hackwould 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..
我认为HollyStyles 的 Hack会起作用(尽管我会担心将 Replace 放入 QueryString - obv。取决于用例),但是有一件事困扰着我..
If the target page is not reading it, why do you need to remove it from the QueryString?
如果目标页面没有读取它,为什么需要将其从 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.
如果做不到这一点,我认为您只需要硬着头皮创建一个 util 方法来为您更改集合。
UPDATE - Following Response from OP
更新 - 以下来自 OP 的回应
Ahhhh! I see now, yes, I have had similar problems with SiteMap performing full comparison of the string.
啊哈!我现在明白了,是的,我在 SiteMap 执行字符串的完整比较时遇到了类似的问题。
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 :)
这样你就再也不用担心这些问题了:)
回答by hollystyles
The search page appends "&terms=" to the query string for highlighting, so it messes it up.
搜索页面将“&terms=”附加到查询字符串以进行突出显示,因此将其弄乱了。
Only other option is a regex replace. If you know for surethat &terms is in the middle of the collection somewhere leave the trailing & in the regex, if you know for sureit's on the end then drop the trailing & and change the replacement string "&" to String.Empty
只有其他选项是正则表达式替换。如果您确定&terms 位于集合中间的某个地方,请在正则表达式中保留尾随 &,如果您确定它在末尾,则删除尾随 & 并将替换字符串“&”更改为 String.Empty
Response.Redirect(String.Format("nextpage.aspx?{0}", Regex.Replace(Request.QueryString.ToString(), "&terms=.*&", "&"));
回答by Ziad
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:
您可以通过处理它的副本来避免触及原始查询字符串。然后,您可以将页面重定向到包含修改后的查询字符串的 url,如下所示:
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);
回答by alex1kirch
HttpUtility.ParseQueryString(Request.Url.Query)
return isQueryStringValueCollection
. It is inherit from NameValueCollection
.
HttpUtility.ParseQueryString(Request.Url.Query)
回报是QueryStringValueCollection
。它是从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);
回答by Answer
Request.Url.GetLeftPart(UriPartial.Path)
should do this
Request.Url.GetLeftPart(UriPartial.Path)
应该这样做
回答by Chris
I found this was a more elegant solution
我发现这是一个更优雅的解决方案
var qs = HttpUtility.ParseQueryString(Request.QueryString.ToString());
qs.Remove("item");
Console.WriteLine(qs.ToString());
回答by biofractal
Here is a solution that uses LINQ against the Request.QueryString
which allows for complex filtering of qs params if required.
这是一个使用 LINQ 的解决方案,Request.QueryString
它允许在需要时对 qs 参数进行复杂过滤。
The example below shows me filtering out the uid
param to create a relative url ready for redirection.
下面的示例显示我过滤掉uid
参数以创建一个准备重定向的相对 url。
Before: http://www.domain.com/home.aspx?color=red&uid=1&name=bob
前: http://www.domain.com/home.aspx?color=red&uid=1&name=bob
After: ~/home.aspx?color=red&name=bob
后: ~/home.aspx?color=red&name=bob
Remove QS param from url
从 url 中删除 QS 参数
var rq = this.Request.QueryString;
var qs = string.Join("&", rq.Cast<string>().Where(k => k != "uid").Select(k => string.Format("{0}={1}", k, rq[k])).ToArray());
var url = string.Concat("~", Request.RawUrl.Split('?')[0], "?", qs);