【问题标题】:Post Async Request with JSON body in c# not working [closed]在c#中使用JSON正文发布异步请求不起作用[关闭]
【发布时间】:2020-12-07 08:01:39
【问题描述】:

我正在尝试使用 c# 中的一些简单 JSON 正文执行 POST 请求。我正在使用 HttpClient 来执行请求。我正在尝试以下方法:

    using (var httpClient = new HttpClient { BaseAddress = baseAddress })
    {
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", cred.Access_token);

        var json = JsonConvert.SerializeObject("{'filter' : {'updated_since' : '2020-12-05T13:11:19+00:00'}}");

        var data = new StringContent(json, Encoding.UTF8, "application/json");

        HttpResponseMessage httpResponseMessage = await httpClient.PostAsync("invoices.list", data).ConfigureAwait(false);

        ...
    }

我在 JSON 字符串中添加了一个简单的过滤器,但结果过滤器不起作用,我得到了所有结果。当我在 Postman 中尝试相同的操作时,一切正常。所以我认为JSON字符串存在一些问题。

邮递员中的 JSON:

{
    "filter": {
        "updated_since": "2020-12-05T13:11:19+00:00"
    }
}

我在这里做错了吗?

【问题讨论】:

  • json 不是你想象的那样。很大程度上是因为您没有序列化 object。您正在序列化一个 string.
  • 我怀疑你的意思是这样的:var json = JsonConvert.SerializeObject(new { filter = new { updated_since = "2020-12-05T13:11:19+00:00" }});
  • @mjwills,谢谢!我确实忘记了对字符串进行序列化。它现在就像我想要的那样工作。谢谢。
  • I indeed forgot to Serialize the string. 好吧,更重要的是您将其序列化 两次 - 但您得到它的工作真是太棒了。
  • 您根本不需要使用序列化,因为您拥有的字符串实际上是有效的 JSON,可以直接传递。

标签: c# json post httpclient


【解决方案1】:

就像@mjwills在评论中说的,我Serialize不是一个对象,而是一个字符串。

我变了

var json = JsonConvert.SerializeObject("{'filter' : {'updated_since' : '2020-12-05T13:11:19+00:00'}}");

var json = JsonConvert.SerializeObject(new { filter = new { updated_since = "2020-12-05T13:11:19+00:00" }});

现在一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 2017-02-12
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    相关资源
    最近更新 更多