HttpClient PostAsync posting null content

断了今生、忘了曾经 提交于 2019-12-05 07:32:51

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!