首页 > 解决方案 > 使用 HttpClient 发布 JSON 数据时出现错误 400

问题描述

我正在尝试以JSON格式将数据发布到 API:

我的JSON数据是:

{
    "itemData": {
                 "Name": "test",
                 "Priority": "High",
                 "SpecificContent": {},
                 "DeferDate": "2019-01-22T11:21:09.431Z",
                 "DueDate": "2019-01-22T11:21:09.432Z",
                 "Reference": "toto"
                }
           }

我的代码:

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", mytoken);
    var res = client.PostAsync(MyURL,
      new StringContent(JsonConvert.SerializeObject(new { ItemData = new { Name = "toto", Priority = "High", SpecificContent = new { } } }),
        Encoding.UTF8, "application/json"));

    try
    {
        res.Result.EnsureSuccessStatusCode();
        MessageBox.Show(res.Result.EnsureSuccessStatusCode().ToString());
    }
    catch (Exception e)
    {
        MessageBox.Show(e.ToString());
    }
}

我有一个错误:

statusCode: 400 错误请求

我的代码有什么问题?

感谢您的帮助

标签: c#jsonpostdotnet-httpclient

解决方案


早晨!

400 错误请求 -

这只是意味着您发送的请求有一些不合适的地方。

https://www.ionos.com/digitalguide/hosting/technical-matters/http-400-bad-request-finding-the-causes/

我的第一个检查通常是确保您发送的对象与 API 端点所期望的数据完全相同:也许您可以向我们提供您正在调用的 API 的一些详细信息?


推荐阅读