JJ Edgar VI JJ Edgar VI - 11 months ago 62
C# Question

C# WebClient not posting data correctly to PHP script


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


$key = $_POST["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 Source

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

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 }