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); }
Nkosi source share