UPDATE: See the comments for a better way to do this!


HttpClient comes with handy methods for the very common task of posting JSON to a web service using the various PostAsJsonAsync methods. It handles serializing your object and crafting up the http request for you, aka

var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };  
Uri gizmoUri = null;

response = client.PostAsJsonAsync("api/products", gizmo).Result;  
if (response.IsSuccessStatusCode)  
{
    gizmoUri = response.Headers.Location;
}
else  
{
    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}

However, what happens if you need to add a custom header to your request? The only way to add a custom header is to craft up an HttpRequestMessage. And the nifty PostAsJsonAsync won’t take a HttpRequestMessage as a parameter; you have to use the SendAsync method.  No sweat; you have to write a little more code but it is no big deal. Here’s what it looks like:

var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" }; 
Uri gizmoUri = null;
MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter(); HttpContent content = new ObjectContent<Product>(gizmo , jsonFormatter); var request = new HttpRequestMessage() { RequestUri = new Uri("api/products"), Method = HttpMethod.Post, Content = content }; request.Headers.Add("My-Special-Header", "xx-oo-xx-oo"); var response = _httpClient.SendAsync(request).Result;