Search code examples
jsonposthttpclient

Using HTTPClient to send JSON content as a string with application/json content type


I'm using an HTTPClient in a C# project and I'm trying to send JSON content with a JSON content type. The POST messages always send as form data.

HttpClient client = new HttpClient();


WorkRequest workRequest = new WorkRequest()
{
   f1 = "asdf",
   ....
};

var content = new StringContent(JsonConvert.SerializeObject(workRequest));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

// Send the ACK request to the workflow for final processing
await client.PostAsync(oxxoWorkflowAckUri, content);

I've tried countless samples I found online, and it's always sent as content type form data.

Anyone know what I'm doing wrong?

Thank you


Solution

  • Your code is mostly correct but the StringContent constructor doesn't automatically set the content type to JSON, so if you manually set the header after creating the StringContent, it can sometimes fail to apply.

    Set the Content-Type directly in the Constructor:

    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text.Json;
    
    HttpClient client = new HttpClient();
    
    WorkRequest workRequest = new WorkRequest
    {
       f1 = "asdf",
    };
    
    string jsonString = JsonSerializer.Serialize(workRequest);
    
    var content = new StringContent(jsonString, System.Text.Encoding.UTF8, "application/json");
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    
    await client.PostAsync(oxxoWorkflowAckUri, content);
    

    Edited.