POSTing JSON data using HttpClient

Recently I’ve been putting together a POC in C# that uses a RESTfull service and while there are tons of examples on how to GET data back there is very little info on how to POST data, specially if you want to POST back JSON content.

So here is a simple example, note I’ve used JSON.NET and I’m making use of the dynamic variable only available in C# 4 and above.

using (var client = new HttpClient())
{
    var request = new CreateAppRequest()
    {
        userAgent = "myAgent",
        endpointId = "1234",
        culture = "en-US"
    };

    var response = client.PostAsync("https://domain.com/CreateApp", 
        new StringContent(JsonConvert.SerializeObject(request).ToString(), 
            Encoding.UTF8, "application/json"))
            .Result;

    if (response.IsSuccessStatusCode)
    {
        dynamic content = JsonConvert.DeserializeObject(
            response.Content.ReadAsStringAsync()
            .Result);

        // Access variables from the returned JSON object
        var appHref = content.links.applications.href;
    }
}

Source: POSTing JsonObject With HttpClient From New REST API (preview release 4)