【问题标题】:415 Unsupported Media Type Error being returned when posting to API through C# class通过 C# 类发布到 API 时返回 415 Unsupported Media Type Error
【发布时间】: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"));
  • 所以情况不同

标签: c# .net json api


【解决方案1】:

换行

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多