简体   繁体   中英

The PostAsync in HttpClient doesn't send data to my webapi

I've created a HttpClient instance to invoke an API with post method.

    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; }
      
    }

When I check my API out , I receive ApplicantId of my object is Null. 在此处输入图片说明

I cant not figure out why ApplicantId is Null.

Finally I've changed my [FromForm] to [FromBody] in my API and it worked correctly but it stuck on this line var response = await client.PostAsync(url, data); and doesn't go on.

the await keyboard make my app stuck ,I've changed it this way var response = await client.PostAsync(url, data).ConfigureAwait(false); but I didn't figure it out why it cause this problem.

If you using FromForm attribute, you should use FormUrlEncodedContent instead of StringContent as content type when you send POST message. If you still want send json - change FromForm at IsCoolegeStudent method to FromBody .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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