为什么Request.Form.ToString()的返回值与NameValueCollection.ToString()的结果不同

似乎HttpContext.Request.Form中的ToString()被装饰,因此当直接在NameValueCollection上调用时,结果与从ToString()返回的结果不同:

NameValueCollection nameValue = Request.Form; string requestFormString = nameValue.ToString(); NameValueCollection mycollection = new NameValueCollection{{"say","hallo"},{"from", "me"}}; string nameValueString = mycollection.ToString(); return "RequestForm: " + requestFormString + "

NameValue: " + nameValueString;

结果如下:

RequestForm:say = hallo&from = me

NameValue:System.Collections.Specialized.NameValueCollection

我怎样才能得到“string NameValueString = mycollection.ToString();” 返回“say = hallo&from = me”?

您没有看到格式良好的输出的原因是因为Request.Form实际上是System.Web.HttpValueCollection类型。 此类重写ToString()以便它返回所需的文本。 标准NameValueCollection不会覆盖ToString() ,因此您将获得object版本的输出。

如果无法访问该类的专用版本,您需要自己迭代该集合并构建字符串:

 StringBuilder sb = new StringBuilder(); for (int i = 0; i < mycollection.Count; i++) { string curItemStr = string.Format("{0}={1}", mycollection.Keys[i], mycollection[mycollection.Keys[i]]); if (i != 0) sb.Append("&"); sb.Append(curItemStr); } string prettyOutput = sb.ToString(); 

你需要迭代mycollection并自己构建一个字符串,格式化你想要的方式。 这是一种方法:

 StringBuilder sb = new StringBuilder(); foreach (string key in mycollection.Keys) { sb.Append(string.Format("{0}{1}={2}", sb.Length == 0 ? string.Empty : "&", key, mycollection[key])); } string nameValueString = sb.ToString(); 

简单地在NameValueCollection上调用ToString()的原因是Object.ToString()方法实际上是被调用的,它(除非被覆盖)返回对象的完全限定类型名称。 在这种情况下,完全限定的类型名称是“System.Collections.Specialized.NameValueCollection”。

另一种运作良好的方法:

 var poststring = new System.IO.StreamReader(Request.InputStream).ReadToEnd();