开发者

Why is the return value of Request.Form.ToString() different from the result of NameValueCollection.ToString()

开发者 https://www.devze.com 2023-03-27 23:54 出处:网络
It seems like the ToString () in HttpContext.Request.Form is decorated so the result is different from the one returned from ToString() whencalled directly on a NameVa开发者_开发百科lueCollection:

It seems like the ToString () in HttpContext.Request.Form is decorated so the result is different from the one returned from ToString() whencalled directly on a NameVa开发者_开发百科lueCollection:

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;

The result is as the following:

RequestForm: say=hallo&from=me

NameValue: System.Collections.Specialized.NameValueCollection

How can I get "string NameValueString = mycollection.ToString();" to return "say=hallo&from=me"?


The reason you don't see the nicely formatted output is because Request.Form is actually of type System.Web.HttpValueCollection. This class overrides ToString() so that it returns the text you want. The standard NameValueCollection does not override ToString(), and so you get the output of the object version.

Without access to the specialized version of the class, you'll need to iterate the collection yourself and build up the string:

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();


You need to iterate over mycollection and build a string up yourself, formatted the way that you want it. Here's one way to do it:

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();

The reason that simply calling ToString() on your NameValueCollection does not work is that the Object.ToString() method is what's actually being called, which (unless overridden) returns the object's fully qualified type name. In this case, the fully qualified type name is "System.Collections.Specialized.NameValueCollection".


Another method that works well:

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

精彩评论

暂无评论...
验证码 换一张
取 消