好像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 + "<br /><br />NameValue: " + nameValueString;
结果如下:
请求表:say=hello&from=me
NameValue:System.Collections.Specialized.NameValueCollection
如何获得“string NameValueString = mycollection.ToString();”返回“say=hallo&from=me”?
您看不到格式良好的输出的原因是Request.Form
实际上是类型System.Web.HttpValueCollection
。这个类覆盖了ToString()
以便它返回您想要的文本。标准NameValueCollection
does not覆盖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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)