A Mutable Log

A blog by Devendra Tewari


Project maintained by tewarid Hosted on GitHub Pages — Theme by mattgraham

Send content using PUT method

This post demonstrates how to send content to server from a client application written in C#. A typical REST API implements PUT methods to receive content from clients. I’ve been using RestSharp for most REST requests, but this is one use case it doesn’t provide for.

It is fairly easy to implement using .NET’s HttpClient class

Uri uri = ...
byte[] content = ...
string contentType = ... 

HttpClient client = new HttpClient();
ByteArrayContent httpContent = new ByteArrayContent(content);
httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
Task<HttpResponseMessage> put = client.PutAsync(uri, httpContent);
HttpResponseMessage response = put.Result;

Task<string> read = response.Content.ReadAsStringAsync();

if (response.StatusCode == HttpStatusCode.Created)
    // use read.Result