Erric J Manderin
Erric J Manderin

Reputation: 1096

HttpClient PostAsync Invalid Post Format

I am trying to use HttpClient's PostAsync to login to a website; However it always fails and when I tracked the connection using WireShark I found that it posts the data incorrectly

Code

var content = new FormUrlEncodedContent(new[] 
{
    new KeyValuePair<string, string>("value1", data1),
    new KeyValuePair<string, string>("value2", data2),
    new KeyValuePair<string, string>("value3", data3)
});

or

var content = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("value1", data1), 
    new KeyValuePair<string, string>("value2", data2), 
    new KeyValuePair<string, string>("value3", data3)
};

usage

httpClient.PostAsync(postUri, content)

Expectations

value1=123456&value2=123456&value3=123456

Reality

//It adds strange += which makes the post fail...
value1=123456&value2+=123456&value3+=123456

Upvotes: 8

Views: 7718

Answers (3)

Eugenio Mir&#243;
Eugenio Mir&#243;

Reputation: 2428

in my opinion this is nicer to see:

var variables = new Dictionary<string, string>() {
    { "value1", value1 },
    { "value2", value2 }
};
var content = new FormUrlEncodedContent(variables);

and a dictionary can be useful to check for repeated values when loading it, unless you need repeated keys...

Upvotes: 0

Liel
Liel

Reputation: 2437

I Know this works:

var values = new List<KeyValuePair<string, string>>();

values.Add(new KeyValuePair<string, string>("Item1", "Value1"));
values.Add(new KeyValuePair<string, string>("Item2", "Value2"));
values.Add(new KeyValuePair<string, string>("Item3", "Value3"));

using (var content = new FormUrlEncodedContent(values))
{
    client.PostAsync(postUri, content).Result)
}

Upvotes: 4

Martijn van Put
Martijn van Put

Reputation: 3313

Trim the parameters for possible whitespaces. Whitespaces result in a +

var content = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("value1", data1.Trim()), 
    new KeyValuePair<string, string>("value2", data2.Trim()), 
    new KeyValuePair<string, string>("value3", data3.Trim())
};

Upvotes: 1

Related Questions