NameValueCollection 到 URL 查询? [英] NameValueCollection to URL Query?
问题描述
我知道我可以做到这一点
I know i can do this
var nv = HttpUtility.ParseQueryString(req.RawUrl);
但是有没有办法将其转换回网址?
But is there a way to convert this back to a url?
var newUrl = HttpUtility.Something("/page", nv);
推荐答案
只需在 NameValueCollection
上调用 ToString()
将返回 中的名称值对name1=value1&name2=value2
查询字符串就绪格式.请注意,NameValueCollection
类型实际上并不支持这一点,建议这样做会产生误导,但由于实际返回的内部类型,行为在这里起作用,如下所述.
Simply calling ToString()
on the NameValueCollection
will return the name value pairs in a name1=value1&name2=value2
querystring ready format. Note that NameValueCollection
types don't actually support this and it's misleading to suggest this, but the behavior works here due to the internal type that's actually returned, as explained below.
感谢@mjwills 指出 HttpUtility.ParseQueryString
方法实际上返回一个内部 HttpValueCollection
对象而不是常规的 NameValueCollection
(尽管文档指定了NameValueCollection
).HttpValueCollection
在使用 ToString()
时自动对查询字符串进行编码,因此无需编写循环遍历集合并使用 UrlEncode
的例程方法.已经返回了想要的结果.
Thanks to @mjwills for pointing out that the HttpUtility.ParseQueryString
method actually returns an internal HttpValueCollection
object rather than a regular NameValueCollection
(despite the documentation specifying NameValueCollection
). The HttpValueCollection
automatically encodes the querystring when using ToString()
, so there's no need to write a routine that loops through the collection and uses the UrlEncode
method. The desired result is already returned.
获得结果后,您可以将其附加到 URL 并重定向:
With the result in hand, you can then append it to the URL and redirect:
var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
string url = Request.Url.AbsolutePath + "?" + nameValues.ToString();
Response.Redirect(url);
目前使用 HttpValueCollection
的唯一方法是使用上面显示的 ParseQueryString
方法(当然除了反射).看起来这不会改变,因为 请求公开此类的连接问题 已关闭,状态为无法修复".
Currently the only way to use a HttpValueCollection
is by using the ParseQueryString
method shown above (other than reflection, of course). It looks like this won't change since the Connect issue requesting this class be made public has been closed with a status of "won't fix."
顺便说一句,您可以调用 nameValues
上的 Add
、Set
和 Remove
方法来修改附加之前的任何查询字符串项目.如果您对此感兴趣 请参阅我对另一个问题的回答.
As an aside, you can call the Add
, Set
, and Remove
methods on nameValues
to modify any of the querystring items before appending it. If you're interested in that see my response to another question.
这篇关于NameValueCollection 到 URL 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!