Kahn Kahn - 1 year ago 129
C# Question

How to get POST data as array with C#

I'm developing an ASP.NET handler with C# that receives an array of data posted from an external Flash program. How can I use the data as array? It seems the HTTP Context used in ASP.NET automatically html-decodes the post data so that it comes out as a simple string. The separator in this case is comma (could be it's always a comma, never worked with this before).

Seems I need either of two things:

1) A way to get to the data in its html-encoded form, where the comma used as a separator for the arrays can ONLY represent real arrays instead of customer form input (the customer input comma would remain encoded at this point).

2) A way to simulate the PHP

function (don't know PHP myself, but I'm told that does the trick there) to dump the variable into an array.

So any help on how to do either would be appreciated. Thanks in advance!

Edit 1: The data being posted can be for example a bunch of addresses, postalcodes and optional extra info. Such as
. In that example, there were two addresses (
equals whitespace), two postalcodes, but only the second address contained
as the space before the comma was empty. Now once more, as English isn't my mothertongue, the problem was that possible customer-written comma gets mixed with the actual array-splitting comma after decoding.

Answer Source
public void ProcessRequest(HttpContext context)
    using (var reader = new StreamReader(context.Request.InputStream))
        string postedData = reader.ReadToEnd();
        foreach (var item in postedData.Split(new [] { '&' }, StringSplitOptions.RemoveEmptyEntries))
            var tokens = item.Split(new [] { '=' }, StringSplitOptions.RemoveEmptyEntries);
            if (tokens.Length < 2)
            var paramName = tokens[0];
            var paramValue = tokens[1];
            var values = paramValue.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var value in values)
                var decodedValue = context.Server.UrlDecode(value);
                // Do something with the decoded value which corresponds to paramName
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download