C# HttpClient PostAsync request is returning a Bad Request status

115 Views Asked by At

When running the below C# HttpClient PostAsync request I am getting a bad request status. I'm not sure why this is. I have a username and password that I am passing. Not sure whether I am adding that correctly. New to this.

using (var client = new HttpClient())
{
    var data = "{'Locations' : '[50.452603, 30.522025]'}";
    var endpoint = new Uri("https://api.connect.test.com/risk/v3/countr/pop/location?");
    var newPostJson = JsonConvert.SerializeObject(data);
    var payload = new StringContent(newPostJson, Encoding.UTF8, "application/json");
    var byteArray = Encoding.ASCII.GetBytes("username:password");
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
    var status = client.PostAsync(endpoint, payload).Result.StatusCode.ToString();
    Console.WriteLine(status);
}
1

There are 1 best solutions below

0
On BEST ANSWER

First of all data is not a valid json.

var data = "{'Locations' : '[50.452603, 30.522025]'}";

It should be

var data = "{\"Locations\" : [50.452603, 30.522025]}";

This way, you can pass it directly to StringContent.

var payload = new StringContent(data, Encoding.UTF8, "application/json");

If you really want to use that JsonConvert.Serialize, you can make a POCO to store the data.

public class Location
{
    public List<double> Locations = new List<double>();
}