0

I am trying to post a request with following code, I have this code which fails (server complains bad request, as I have no control over server so dont know what server does.)

private static readonly HttpClient client = new HttpClient();     
var values = new Dictionary<string, string>{
                    { "x", "value" }};
var content  = new FormUrlEncodedContent(values);
var response = await client.PostAsync(postUrl, content);

and then I have this code which works

private static readonly HttpClient client = new HttpClient();     
var values = new Dictionary<string, string>{
                    { "x", "\"value\"" }};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(postUrl, content);

Only difference is my value has extra "" around it. Can anyone please why it is happening? Or if I should have used something else?

2
  • 3
    What do you mean by "works" and "fails"? Which server are you posting to? The first posts a body of x=value; the second posts a body of x=%22value%22. What any particular server does with those bodies is up to that server. Commented Jun 1, 2018 at 5:58
  • 1
    This question "failed" to put the relevant information and error status codes, to make it clear Commented Jun 1, 2018 at 6:03

2 Answers 2

1

In the one that works, you are escaping the quotes. That’s what’s enabling it work. It means that most likely the value is separated by a space. That is, it contains two words. Usually you have to do a url encode for the value or you just keep it in quotes. So when you escape the quotes with the /“ you are sending it to the server with the quotes hence it’s working.

Sign up to request clarification or add additional context in comments.

Comments

1

Let's consider this sample program.

static void Main(string[] args)
{
    Show(new Dictionary<string, string> { { "x", "value" } });
    Show(new Dictionary<string, string> { { "x", "\"value\"" } });
}

private static async void Show(Dictionary<string, string> values)
{
    var content = new FormUrlEncodedContent(values);
    var body = await content.ReadAsStringAsync();
    Console.WriteLine(body);
}

The output is: x=value x=%22value%22

In the first case when the server reads the body it sees x=value, and value is not a string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.