【问题标题】:The PostAsync in HttpClient doesn't send data to my webapiHttpClient 中的 PostAsync 不会将数据发送到我的 webapi
【发布时间】:2020-09-30 10:19:34
【问题描述】:

我创建了一个 HttpClient 实例来调用带有 post 方法的 API。

    using (var client = new HttpClient())
            {
           
                var person = new Stu();
                person.ApplicantId = "48751889-D86E-487B-9508-000EAB65F11F";
                

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

                var url = "http://localhost:52085/api/CollegeService/IsCoolegeStudent";
                // var client = new HttpClient();

                var response = await client.PostAsync(url, data);

                string result = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(result);

            }
    public class Stu
    {
        public string ApplicantId { get; set; }
      
    }

当我检查我的 API 时,我收到我的对象的申请者 ID 为空。

我不明白为什么申请人 ID 为 Null。

最后,我在我的 API 中将[FromForm] 更改为[FromBody],它工作正常,但卡在 var response = await client.PostAsync(url, data); 这一行上并且无法继续。

await 键盘让我的应用卡住了,我已经这样改了 var response = await client.PostAsync(url, data).ConfigureAwait(false); 但我没有弄清楚为什么会导致这个问题。

【问题讨论】:

  • 当你到达断点时。使用调试:windows:调用堆栈。然后你可以点击父方法来查看“s”的设置位置。
  • 我可以看到在调用堆栈中调用的方法的顺序,对吧?
  • 对。其中一位父母没有正确设置 id。您应该能够单击父母并将鼠标悬停在变量上以查看 id 设置不正确的位置。

标签: c# httpclient webapi


【解决方案1】:

如果你使用FromForm属性,你应该在发送POST消息时使用FormUrlEncodedContent而不是StringContent作为内容类型。如果您仍想发送 json - 将 IsCoolegeStudent 方法中的 FromForm 更改为 FromBody

【讨论】:

  • 我已将其更改为 FromForm 并且它可以正常工作,但它会卡在这一行' var response = await client.PostAsync(url, data);'
  • 您的服务器应用程序中是否还有断点?如果是 - 您的客户端正在等待服务器代码的执行。
  • 我删除了服务器上的所有断点,但是在我调用我的服务的地方它卡在了这一行'var response = await client.PostAsync(url, data);'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
  • 1970-01-01
  • 1970-01-01
  • 2019-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多