Send a file via HTTP POST with C#

Using .NET 4.5 (or .NET 4.0 by adding the Microsoft.Net.Http package from NuGet) there is an easier way to simulate form requests. Here is an example: private async Task<System.IO.Stream> Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes) { HttpContent stringContent = new StringContent(paramString); HttpContent fileStreamContent = new StreamContent(paramFileStream); HttpContent bytesContent = new ByteArrayContent(paramFileBytes); using … Read more

Checking if HttpStatusCode represents success or failure

If you’re using the HttpClient class, then you’ll get a HttpResponseMessage back. This class has a useful property called IsSuccessStatusCode that will do the check for you. using (var client = new HttpClient()) { var response = await client.PostAsync(uri, content); if (response.IsSuccessStatusCode) { //… } } In case you’re curious, this property is implemented as: … Read more

Usage of EnsureSuccessStatusCode and handling of HttpRequestException it throws

The idiomatic usage of EnsureSuccessStatusCode is to concisely verify success of a request, when you don’t want to handle failure cases in any specific way. This is especially useful when you want to quickly prototype a client. When you decide you want to handle failure cases in a specific way, do not do the following. … Read more