Post string to Rest API 导致 400 Bad Request

Post string to Rest API results in 400 Bad Request

发送 post 请求,其中 json 对象转换为 HttpContent,但结果是 400 Bad 请求。

发件人

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"));

接收者

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

能否请你给我一个关于如何克服 400 错误的建议?

您的调用中似乎多了一个括号

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

(

先尝试删除它。

干杯

您当前的代码发送一个 object 序列化为 jsonASP.NET Core 操作期望一个 string 序列化为json。最简单的解决方案是重复数据序列化

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