Home > Software engineering >  C# HttpClient: How to send query strings in POST Requests
C# HttpClient: How to send query strings in POST Requests

Time:09-22

This is the POST Request, it works.

curl -X POST --header 'Accept: application/json' 

'http://mywebsite.com/api/CompleteService?refId=12345&productPrice=600'

How to send this request using C# => HttpClient => client.PostAsync() method? Two methods have been tried but both failed.


Method 1 (Failed, Response 404)

string url = "http://mywebsite.com/api/CompleteService";
string refId = "12345";
string price= "600";
string param = $"refId ={refId}&productPrice={price}";
HttpContent content = new StringContent(param, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(url, content).Result;

This would only work if API is to accept a request body, not query strings.


Method 2 (Failed, Response 404) https://stackoverflow.com/a/37443799/7768490

var parameters = new Dictionary<string, string> { { "refId ", refId }, { "productPrice", price} };
var encodedContent = new FormUrlEncodedContent(parameters);
HttpResponseMessage response = client.PostAsync(url, encodedContent)

CodePudding user response:

Apparently, None of the tried approaches put parameters in the URL!. You are posting on the below URL

"http://mywebsite.com/api/CompleteService"

However, something that works

string url = "http://mywebsite.com/api/CompleteService?";
string refId = "12345";
string price= "600";
string param = $"refId={refId}&productPrice={price}";
HttpContent content = new StringContent(param, Encoding.UTF8, "application/json");

Attach Parameters to URL and to get Response's Body, Use:

  try   
  {
     HttpResponseMessage response = await client.PostAsync(url   param, content);
     response.EnsureSuccessStatusCode();
     string responseBody = await response.Content.ReadAsStringAsync();
     Console.WriteLine(responseBody);
  }
  catch(HttpRequestException e)
  {
     Console.WriteLine("Message :{0} ",e.Message);
  }
  • Related