Sunday, April 19, 2015

Bing-Mail Easy Post Api - Version 1.3 - C#

Recently I had a chance to integrate an awesome and innovative postal mailing API ( in my system. However I ran into some problems because their code samples were in PHP and doing the same from .NET was giving me errors. Finally I found a solution and may be someone out there will benefit from it.

The most frustrating error I had to fix was uploading files as a PUT HTTP method with Digest Authentication.

Complete solution except some easy-to-figure-out methods are posted in this gist. Bing-Mail Easy Post Api - Version 1.3

What i did was modified the DigestAuthFixer from to support any HTTP method.

Then used that to create the session, when we create the session using DigestAuthFixer it stores the Digest-Auth headers which i can reuse when uploading the files.
 using (var client = new WebClient())
    var uri = new Uri(_easypostHosts[2] + UploadUri.FormatWith(sessionId, HttpUtility.UrlEncode(fileName)));

    // get the auth headers which are already stored when we create the session
    var digestHeader = DigestAuthFixer.GetDigestHeader(uri.PathAndQuery, "PUT");
    // add the auth header to our web client
    client.Headers.Add("Authorization", digestHeader);

    // trying to use the UploadFile() method doesn't work in this case. so we get the bytes and upload data directly 
    byte[] fileBytes = File.ReadAllBytes(filePath);

    // as a PUT request
    var result = client.UploadData(uri, "PUT", fileBytes);

    // result is also a byte[].
    content = result.Length.ToString();