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, yet. It is fairly easy to implement using .NET’s HttpClient.

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s