JJ Edgar VI JJ Edgar VI - 1 month ago 11
C# Question

C# WebClient not posting data correctly to PHP script

C#:

using (WebClient client = new WebClient()) {
byte[] response = client.UploadValues("http://example.com/api/server/key",
new NameValueCollection() {
{ "key", key }
});

string result = Encoding.UTF8.GetString(response);
Console.WriteLine(result);
}


PHP:

$key = $_POST["key"];
echo($key);


When this runs, the PHP $_POST array never has any value actually posted to it. Meaning that the echo line has no output.

Also, yes, 'key' does have a value, it is just cropped out in this example.

Answer

I am not sure, the expression new NameValueCollection() { ... } does what you think it should do.

You should be explicit and say

NameValueCollection values = new NameValueCollection();
values.Add("key", key);
byte[] response = client.UploadValues("http://example.com/api/server/key",
                                      values);

Searching for object initializers reveals Collection initializers

Collection initializers let you specify one or more element initializers when you initialize a collection class that implements IEnumerable or a class with an Add extension method.

And an example

List<Cat> cats = new List<Cat>
{
    new Cat(){ Name = "Sylvester", Age=8 },
    new Cat(){ Name = "Whiskers", Age=2 },
    new Cat(){ Name = "Sasha", Age=14 }
};

So maybe using the initializer without the parentheses works, e.g.

byte[] response = client.UploadValues("http://example.com/api/server/key",
                                      new NameValueCollection {
                                          { "key", key }
                                      });