【问题标题】:Why is the return value of Request.Form.ToString() different from the result of NameValueCollection.ToString()为什么 Request.Form.ToString() 的返回值与 NameValueCollection.ToString() 的结果不同
【发布时间】:2011-08-15 14:16:56
【问题描述】:

好像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;

结果如下:

RequestForm:say=hallo&from=me

NameValue:System.Collections.Specialized.NameValueCollection

如何获得“字符串 NameValueString = mycollection.ToString();”返回“say=hallo&from=me”?

【问题讨论】:

    标签: c# .net asp.net asp.net-mvc-3


    【解决方案1】:

    您看不到格式良好的输出的原因是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();
    

    【讨论】:

      【解决方案2】:

      您需要遍历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() method 是实际调用的对象,它(除非被覆盖)返回对象的完全限定类型名称。在这种情况下,完全限定的类型名称是“System.Collections.Specialized.NameValueCollection”。

      【讨论】:

        【解决方案3】:

        另一种效果很好的方法:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-10-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-27
          • 2012-07-28
          • 2013-03-10
          • 1970-01-01
          • 2018-02-08
          相关资源
          最近更新 更多