繁体   English   中英

HttpClient 中的 PostAsync 不向我的 webapi 发送数据

[英]The PostAsync in HttpClient doesn't send data to my 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 为空。 在此处输入图片说明

我不明白为什么申请人 ID 是空的。

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

等待键盘让我的应用程序卡住了,我已经改变了这种方式var response = await client.PostAsync(url, data).ConfigureAwait(false); 但我不明白为什么会导致这个问题。

如果使用FromForm属性,则在发送 POST 消息时应使用FormUrlEncodedContent而不是StringContent作为内容类型。 如果你仍然想发送JSON -改变FromForm在IsCoolegeStudent方法FromBody

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM