Search code examples
c#post.net-corehttpclientrestsharp

HTTP Post Error 400 using RestSharp and HTTPClient - How to Diagnose?


I'm porting a java application to C#. There is an HTTP post request with some key value pairs. No authentication required. I've also been provided a working python example that POSTs in a similar way. The endpoint is good.

I've tried both HTTPClient and RestSharp with similar results.

I wonder if I'm doing this wrong, I'm doing something like this:

var values = new Dictionary<string, string>
                {
                    { "A", a },
                    { "B", b },
                    { "C", c },
                    { "D", d }
                }
var content = new FormUrlEncodedContent(values);
Uri u = new Uri(myURI);
var response = await client.PostAsync(u,content);
var responseString = await response.Content.ReadAsStringAsync();

The python looks very similar to this:

>>> payload = {'key1': 'value1', 'key2': 'value2'}

>>> r = requests.post("https://httpbin.org/post", data=payload)
>>> print(r.text)

The java and python examples, look very similar, building a list of parameters and posting. The rest sharp looks similar, but also fails with the same error. I'm looking for some things to try, that I don't know. Is is a header or content type change? Different way to submit the data? I'm lost here.


Solution

  • Per the comments in the question, Fiddler was suggested to diagnose the issue.

    Fiddler nicely formatted the response text which showed an invalid parameter. Parameter corrected and everything is working.