Hen*_*bæk 11 .net c# asp.net asp.net-mvc-3
似乎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;
Run Code Online (Sandbox Code Playgroud)
结果如下:
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();
Run Code Online (Sandbox Code Playgroud)