Friday, September 28, 2018

What is the WebClient of C# 4.0?

It is a kinda ghetto way of hitting API endpoints before the async/await stuff of C# 5.0. The code below is synchronous and just hangs out until we round trip to someone else's server or blow up in exception.

using System.Net;
using System.Text;
using RefreshCerts.Core.ExternalDependencies;
using RefreshCerts.Core.Objects;
namespace RefreshCerts.Infrastructure.ExternalDependencies
{
   public class ApiInteraction : IApiInteraction
   {
      public string GetToken(Bootstrapping bootstrapping)
      {
         using (WebClient webClient = new WebClient())
         {
            webClient.Headers.Add("Content-Type", "application/json");
            var response = webClient.UploadData(bootstrapping.ApiUrl + "authorize",
                  "POST", Encoding.Default.GetBytes("{\"Username\": \"" +
                  bootstrapping.ApiUsername + "\", \"Password\": \"" +
                  bootstrapping.ApiPassword + "\"}"));
            string token = Encoding.UTF8.GetString(response);
            return token;
         }
      }
   }
}

 
 

Honestly, I may abandon this approach and this may be the only blog posting on this subject. I think I went down the wrong rabbithole. Anyhow, some pain points I hit included this error:

The Content-Type header cannot be changed from its default value for this request.

 
 

The fix for this per this is to include the line above that has "application/json" in it. Another error I hit in orginally trying to craft code like this was:

The remote server returned an error: (415) Unsupported Media Type.

 
 

This came from using an .UploadValues implementation instead of an .UploadData implementaion. In .UploadValues the first two parameters handed in are the same (a URL and a verb) and the third is an object like our stuff object here:

var stuff = new NameValueCollection();
stuff["Username"] = bootstrapping.ApiUsername;
stuff["Password"] = bootstrapping.ApiPassword;

 
 

Alright, on the otherside of the two errors above I get:

The remote server returned an error: (403) Forbidden.

 
 

...but that just means my username and password are wrong.

No comments:

Post a Comment