问题描述
我知道我能做到这一点。
变种NV = HttpUtility.ParseQueryString(req.RawUrl);
但是,有没有办法转换这回网址?
VAR NEWURL = HttpUtility.Something(/页,NV);
简单地调用的ToString()
在的NameValueCollection
查询字符串准备格式>将在名1 =值1&放大器返回名称值对。需要注意的是
的NameValueCollection
类型实际上并不支持这一点,它的误导性暗示这一点,但行为在这里工作,由于这实际上是返回,如下所述的内部类型。
感谢@mjwills的,而不是指出的是,
HttpUtility.ParseQueryString
方法实际上返回内部 HttpValueCollection
对象普通的的NameValueCollection
()。在 HttpValueCollection
自动连接codeS查询字符串使用的ToString()
的时候,所以没有必要写一个例程这循环通过收集和使用 UrlEn code
方法。期望的结果是已经回来了。
通过结果在手,你可以将其添加到URL,并重定向:
VAR nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
字符串的URL = Request.Url.AbsolutePath +? + nameValues.ToString();
的Response.Redirect(URL);
目前使用的唯一方式
HttpValueCollection
是使用上面显示的 ParseQueryString
办法(比反射等,当然)。它看起来像这样因为Connect问题要求该类被公开已关闭的状态为不会解决。
顺便说一句,你可以调用
添加
,设置
和删除
在 nameValues
方法追加之前修改任何查询字符串项目。如果你有兴趣在see我的回答另一个问题。
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);
解决方案
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.
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.
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);
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."
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查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!