postasync c# returns null
As indicated in the comments the model was not being converted to JSON when you called model.ToString. You eventually figured out that you can use Json.Net to serialize the model to JSON with JsonConvert.SerializeObject(model). This will work for serializing the model to JSON.
You could go one step further and create an extension method to perform that functionality 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);
}
}
This will now allow you to call the method on your model and covert it to 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 method that is frequently used basically performs the same thing you eventually realized by abstracting the JSON serialization step for you.
Internally it is calling the same PostAsync method.
which would look something a little 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);
}