我有一个NameValueCollection初始化的usercontrol,如下所示:
private NameValueCollection _nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
Run Code Online (Sandbox Code Playgroud)
当我调用ToString()它时,它会生成一个正确的查询字符串,我可以将其用于更新的URL.
但是,当我NameValueCollection像这样复制via它的构造函数时:
var nameValues = new NameValueCollection(_nameValues);
Run Code Online (Sandbox Code Playgroud)
然后尝试形成一个网址:
var newUrl = String.Concat(_rootPath + "?" + nameValues.ToString());
Run Code Online (Sandbox Code Playgroud)
它会输出一个这样的网址:
" http://www.domain.com?System.Collections.Specialized.NameValueCollection "
如何复制a NameValueCollection以使ToString()方法输出所需的结果?
bbe*_*eda 16
问题是代码中有两种实际类型.第一个是System.Web.HttpValueCollection,它使用ToString方法覆盖以获得您期望的结果,第二个是System.Collection.Specialized.NameValueCollection,它不会覆盖ToString.你可以做什么,如果你真的需要使用System.Collection.Specialized.NameValueCollection就是创建一个扩展方法.
public static string ToQueryString(this NameValueCollection collection)
{
var array = (from key in collection.AllKeys
from value in collection.GetValues(key)
select string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value))).ToArray();
return "?" + string.Join("&", array);
}
Run Code Online (Sandbox Code Playgroud)
并使用它:
var newUrl = String.Concat(_rootPath,nameValues.ToQueryString());
Run Code Online (Sandbox Code Playgroud)