首页 > 解决方案 > HttpClient 中的 PostAsync 不会将数据发送到我的 webapi

问题描述

我创建了一个 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 为空。 在此处输入图像描述

我不明白为什么ApplicantId 是空的。

最后,我在我的 API 中更改了我[FromForm]的 to并且它工作正常,但它卡在这条线上并且没有继续。[FromBody] var response = await client.PostAsync(url, data);

await 键盘使我的应用程序卡住了,我已经以这种方式对其进行了更改, var response = await client.PostAsync(url, data).ConfigureAwait(false); 但我没有弄清楚为什么会导致此问题。

标签: c#httpclientwebapi

解决方案


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


推荐阅读