c# - 通过 C# 类发布到 API 时返回 415 Unsupported Media Type Error
问题描述
我正在尝试编写一个将 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(不支持的媒体类型)。” 我尝试调整传入的字符串的格式,但我得到了同样的错误,所以我想在继续下一步之前,我会询问我可能做错了什么。
解决方案
将线路更改为
var res = client.PostAsync("localhost:44308/TestDev", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject( new { json } ), Encoding.UTF8, "application/json"));
...修复了错误 415。我仍然收到错误,但会将其移至新的讨论。
推荐阅读
- python - 以下是函数 hangman 的最终代码,我收到语法错误
- class - 类图的实体属性查询
- rust - 是否可以实现一个拥有锁的迭代器以及引用该锁的内部迭代器?
- mysql - 关闭 Ubuntu phpmyadmin 区分大小写
- firebase - 如何将列表存储到 Firestore 并在 Flutter 中获取
- azure - 未能在 Azure 中触发自定义 HeartBeat 指标的警报
- java - 如何知道一个字符串是否属于另一个字符串,即使跳过字母也可以计算
- python - 在两个 Flask 应用程序之间共享 Flask-SQLAlchemy
- algorithm - 从具有相同平方和的数组中找到两对整数
- python - Python中的时间残差函数