HttpClient PostAsync publishes empty content

I have one api calling another.

and here is my code which apparently calls ModelState.IsValid = false on the other side of the world.

 var baseUri = new Uri("http://localhost:5001/"): _httpClient.BaseAdress = baseUri; var data = new StringContent(content: model.Tostring(), encoding: Encoding.UTF8, mediaType: "application/json"); var response = await _httpClient.PostAsync("api/product", data); 

look Post([FromBody]Product product) on the called api. I just see product=null .

a change to Post([FromBody]object product) also shows null .

calling api from Postman works fine. which localize my problem to PostAsync . What happens to my PostAsync ?

Edit

I know that people can offer PostAsJsonAsync , but I will try it only after I know what the problem is with PostAsync . PostAsync

+5
source share
1 answer

As pointed out in the comments, model not converted to JSON when calling model.ToString . In the end, you found out that you can use Json.Net to serialize the model for JSON using JsonConvert.SerializeObject(model) . This will work to serialize the model for JSON.

You can take another step and create an extension method to perform this function for you.

 public class JSONStringExtension { public static string ToJsonString(this object model) { if(model is string) throw new ArgumentException("mode should not be a string"); return JsonConvert.SerializeObject(model); } } 

Now this will allow you to call the method on your model and hide it in JSON in your code.

 var baseUri = new Uri("http://localhost:5001/"): _httpClient.BaseAdress = baseUri; var data = new StringContent(content: model.ToJsonString(), //<--Extension method here encoding: Encoding.UTF8, mediaType: "application/json"); var response = await _httpClient.PostAsync("api/product", data); 

The PostAsJsonAsync extension PostAsJsonAsync , which is often used, basically does the very same thing that you eventually implemented, abstracting the JSON serialization step for you. internally, it calls the same PostAsync method.

which will look something like this.

 public static Task<HttpResponseMessage> PostAsJsonAsync(this HttpClient httpClient, string url, object content) { var json = JsonConvert.SerializeObject(content) var data = new StringContent(content: json, encoding: Encoding.UTF8, mediaType: "application/json"); return httpClient.PostAsync(url, data); } 
+2
source

Source: https://habr.com/ru/post/1262835/


All Articles