How to set the Content-Type header for an HttpClient request

The content type can be specified when creating the request content itself.

Note that the example below adds 'application/json'' in two places -- for Accept and Content-Type headers.

var client = new HttpClient();
client.BaseAddress = new Uri("");

// ACCEPT header

     new MediaTypeWithQualityHeaderValue("application/json"));

var request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");

// CONTENT-TYPE header

request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", 
                     Encoding.UTF8, "application/json");

client.SendAsync(request).ContinueWith(responseTask => 
        Console.WriteLine("Response: {0}", responseTask.Result); );

Jack Poorte
Jack Poorte
Last updated on Sep 30, 2023

Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Cookies       Do Not Sell       Licensing      
Made with    in Austin, Texas.  - vsn 44.0.0
© Data & Object Factory, LLC.