[英]415 unsupported media type error when posting to aspnetcore api from angular using $http
[英]415 Unsupported Media Type Error being returned when posting to API through C# class
我正在尝试编写一个 class ,它将一个 json object 发布到 ZDB974238714CA8DE634A7CE1D083A1。 如果我通过 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"}}]
但是,使用 class 时出现错误。
这是我正在尝试使用的 class:
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(不支持的媒体类型)。” 我尝试调整传入的字符串的格式,但我得到了同样的错误,所以我想在继续之前我会询问我可能做错了什么。
将线路更改为
var res = client.PostAsync("localhost:44308/TestDev", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject( new { json } ), Encoding.UTF8, "application/json"));
...修复了错误 415。我仍然收到错误,但会将其移至新的讨论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.