Why is the return value of Request.Form.ToString()

2019-06-15 16:00发布

问题:

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 NameValueCollection:

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"?

回答1:

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


回答2:

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".



回答3:

Another method that works well:

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