DanielV
DanielV

Reputation: 2700

Post string to Rest API results in 400 Bad Request

Sending a post request with a json object transformed into HttpContent, but the result is a 400 Bad request.

Sender

HttpClient _client = new HttpClient();
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept
               .Add(new MediaTypeWithQualityHeaderValue("application/json"));

var jsonObject = new JObject(new JProperty("id", Id), new JProperty("image", face));
var strJson = JsonConvert.SerializeObject(jsonObject);
var response = _client.PostAsync(_settings.Uri, 
                   new StringContent(strJson, Encoding.UTF8, "application/json"));

Receiver

[HttpPost]
public IActionResult Post([FromBody]string value)

Could you please give me an advise on how to overcome 400 error?

Upvotes: 0

Views: 3085

Answers (2)

Alexander
Alexander

Reputation: 9642

You current code sends an object serialized to json while ASP.NET Core action expects a string serialized to json. The easiest solution would be repeated data serialization

var objectJson = JsonConvert.SerializeObject(jsonObject);
var stringJson = JsonConvert.SerializeObject(objectJson);
var response = _client.PostAsync(_settings.Uri, new StringContent(stringJson, Encoding.UTF8, "application/json"));

Upvotes: 1

Matt Falkowski
Matt Falkowski

Reputation: 64

It appears that you have an extra Parentheses in your call

var response = _client.PostAsync(_settings.Uri, (new StringContent(strJson, Encoding.UTF8, "application/json"));

(new

Try removing that first.

Cheers

Upvotes: 2

Related Questions