【发布时间】:2020-09-20 09:07:26
【问题描述】:
我正在尝试编写一个将 json 对象发布到 API 的类。如果我通过 Postman 发布以下内容(将其作为原始 json 传递),API 会以 200 响应:
[{"Id":"1","Name":"First of Two","obdOdometer":{"Time":"2020-01-01","Value":"112233"}},{"Id":"2","Name":"Second of Two","obdOdometer":{"Time":"2020-02-03","Value":"45506"}}]
但是,我在使用我的课程时遇到了错误。
这是我尝试使用的类:
public async Task TransmitobdOdometer(string json)
{
string bearerToken = _config.GetSection("PilotTmwApiSettings:BearerToken").Value;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
var res = client.PostAsync("https://localhost:44308/TestDev", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject( new { json } )));
try
{
res.Result.EnsureSuccessStatusCode();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
传递给 TransmitobdOdometer() 的字符串格式如下:
string odometerValues = "[{\"Id\":\"1\",\"Name\":\"First of Two\",\"obdOdometer\":{\"Time\":\"2020-01-01\",\"Value\":\"112233\"}},{\"Id\":\"2\",\"Name\":\"Second of Two\",\"obdOdometer\":{\"Time\":\"2020-02-03\",\"Value\":\"45506\"}}]";
这将返回错误消息:“响应状态代码未指示成功:415(不支持的媒体类型)。”我尝试调整传入的字符串的格式,但我得到了同样的错误,所以我想在继续之前我会询问我可能做错了什么。
【问题讨论】:
-
您是否尝试将
Content-Type设置为application/json? -
我将一行更改为使用 application/json(见下文),现在我收到错误 400: var res = client.PostAsync("localhost:44308/TestDev", new StringContent(Newtonsoft.Json .JsonConvert.SerializeObject(new { json } ), Encoding.UTF8, "application/json"));
-
所以情况不同