0

I want to pass an object as a parameter to the httpClient's POST request. The object is a Dto which contains all fields required for the POST request. Dto example: (I have created a class - Toolbox elsewhere)

class Toolbox 
{
    public string Date { get; set; }
    public string Index { get; set; }

}
var Toolbox = new toolbox 
{
   Date = "05/08/2022"
   Index = "1"
}

With examples on the internet, I managed to create this code to make a POST request. I wanted to confirm if this is the correct / best way to do so.

public class Class1
    {
        private const string URL = "https://sub.domain.com/objects.json";
        private string urlParameters = "?api_key=123";

        static void Main(string[] args)
        {
            HttpClient client = new HttpClient();

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            // List data response.
            HttpResponseMessage response = client.PostAsync(URL, byteContent).Result;  
            if (response.IsSuccessStatusCode)
            {...}

The signature for the PostAsync method is as follows:

public Task PostAsync(Uri requestUri, HttpContent content)

Since the object to PostAsync it must be of type HttpContent, my custom Dto class does not meet that criteria, and what I can do is:

  1. Serialize my custom type to JSON, the most common tool for this is Json.NET.
var myContent = JsonConvert.SerializeObject(data);
  1. construct a content object to send this data, e.g. ByteArrayContent object (I could use or create a different type (?))
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
  1. set the content type to let the API know this is JSON
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  1. send my request very similar to your previous example with the form content
var response = client.PostAsync("URL", byteContent).Result

May I ask should I do the above steps of converting the type directly below httpClient or should I encapsulate it for a better coding practice? Thank you very much in advance

silverpegasus
  • 91
  • 1
  • 10
  • This is the same question as https://stackoverflow.com/questions/6117101/posting-jsonobject-with-httpclient-from-web-api – Bron Davies Aug 15 '22 at 14:28
  • Does this answer your question? [POSTing JsonObject With HttpClient From Web API](https://stackoverflow.com/questions/6117101/posting-jsonobject-with-httpclient-from-web-api) – Bron Davies Aug 15 '22 at 14:29
  • Thanks for your response. Since mine is a custom object, in fact it's a pretty complicated object (with different layers - object inside object) - but I have simplified it here in the question. So I'm not sure will `ToString()` on my object help? – silverpegasus Aug 15 '22 at 14:31
  • The only thing you really have to worry about in a complex object is whether it is serializable to JSON. The code used in that answer will create a valid json object if there are no circular references in the object – Bron Davies Aug 15 '22 at 14:33

0 Answers0