HttpUtility.ParseQueryString的反向函数

Pal*_*ani 11 asp.net asp.net-mvc namevaluecollection query-string

.Net的System.Web.HttpUtility类定义了以下函数来将查询字符串解析为NameValueCollection:

public static NameValueCollection ParseQueryString(string query);
Run Code Online (Sandbox Code Playgroud)

是否有任何功能可以反向(即将a NameValueCollection转换为查询字符串)?

Iva*_*ton 24

System.Collections.Specialized.NameValueCollection支持这一点,但派生内部类System.Web.HttpValueCollection DOES(通过重写ToString()).

不幸的是(在内部)你不能直接实例化这个类,但是返回一个HttpUtility.ParseQueryString()(你可以调用它String.Empty,但不能Null).

一旦你有了HttpValueCollection,你可以在最后打电话之前NameValueCollection通过电话填写原件.Add()ToString()

var nameValueCollection = new NameValueCollection {{"a","b"},{"c","d"}};
var httpValueCollection = System.Web.HttpUtility.ParseQueryString(String.Empty);
httpValueCollection.Add(nameValueCollection);
var qs = httpValueCollection.ToString();
Run Code Online (Sandbox Code Playgroud)

nameValueCollection.ToString()="System.Collections.Specialized.NameValueCollection"httpValueCollection.ToString()="a = b&c = d"


Dou*_*oug 3

NameValueCollection 有一个自动 ToString() 方法,该方法会自动将所有元素作为查询字符串写出。

你不需要自己写。

var querystringCollection = HttpUtility.ParseQueryString("test=value1&test=value2");

var output = querystringCollection.ToString(); 
Run Code Online (Sandbox Code Playgroud)

输出=“测试=值1&测试=值2”

  • 不正确。“System.Collections.Specialized.NameValueCollection”不支持此功能。这是“System.Web.HttpValueCollection”的一个功能。 (11认同)