2

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. enter image description here

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.

3
  • 2
    When you hit break point. Use Debug : windows : Call Stack. Then you can click on parent methods to see where "s" is being set. Commented Sep 30, 2020 at 10:26
  • I can see the sequence of method that called in call stack ,right? Commented Sep 30, 2020 at 11:01
  • 1
    Right. One of the parents isn't setting the id properly. You should be able to click on parents and the hover over variables to see where id isn't being set properly. Commented Sep 30, 2020 at 11:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I've changed it to FromForm and its work correctly but it will stuck at this line ' var response = await client.PostAsync(url, data);'
Is you still have breakpoint at your server application? If yes - your client awaits execution of server code.
I remove all breakpoints on my server but where I call my service it stucks on this line ' var response = await client.PostAsync(url, data);'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.