首页 > 解决方案 > 通过 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(不支持的媒体类型)。” 我尝试调整传入的字符串的格式,但我得到了同样的错误,所以我想在继续下一步之前,我会询问我可能做错了什么。

标签: c#.netjsonapi

解决方案


将线路更改为

var res = client.PostAsync("localhost:44308/TestDev", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject( new { json } ), Encoding.UTF8, "application/json")); 

...修复了错误 415。我仍然收到错误,但会将其移至新的讨论。


推荐阅读