Chris
Chris

Reputation: 27384

How can I tell if HttpClient is connecting via HTTPS

I am using HttpClient to talk to an API. The server will automatically redirect http:// requests to https:// if enabled. So, in order to protect the users API key I want to create a test connection to the website to see if I am redirected before sending over the API Key.

The HttpClient redirects properly, but I cannot seem to find a decent way to find out if the client is using HTTPS or not. I know I could test whether https:// exists within response.RequestMessage.RequestUri but this seems a little flaky

public void DetectTransportMethod()
{
    using (HttpClient client = new HttpClient())
    {
        client.Timeout = TimeSpan.FromSeconds(20);

        using (HttpResponseMessage response = client.GetAsync(this.HttpHostname).Result)
        {
            using (HttpContent content = response.Content)
            {
                // check if the method is HTTPS or not
            }
        }
    }
}

Upvotes: 1

Views: 2571

Answers (1)

TheDutchDevil
TheDutchDevil

Reputation: 876

The documentation of HttpClient (MSDN) and HttpResponseMessage (MSDN) do not contain any methods that can be used to determine whether a request has been made over https. Even though checking the URI of the HttpResponseMessage does indeed sound flaky I'm afraid it's the easiest and most readable option. Implementing this as a extension method for HttpResponseMessage probably is the most readable. To ensure that the HttpClient you are using can be redirected make sure that the WebRequestHandler (MSDN) passed into the HttpClient has the AllowAutoRedirect (MSDN) property set to true.

See the following extension method:

static class Extensions
{
    public static bool IsSecure(this HttpResponseMessage message)
    {
        rreturn message.RequestMessage.RequestUri.Scheme == "https";
    }
}

And the following Console application that demonstrates it works. For this to work however, the HTTP server has to upgrade the connection to https (Like Facebook does) and the AllowAutoRedirect property of the WebRequestHandler has to be set to true.

static void Main(string[] args)
{
     using (var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = true}))
     {
         client.Timeout = TimeSpan.FromSeconds(20);

         using (var response = client.GetAsync("http://www.geenstijl.nl").Result)
         {
             Console.WriteLine(response.IsSecure());
         }

         using (var response = client.GetAsync("http://www.facebook.com").Result)
         {
             Console.WriteLine(response.IsSecure());
         }
     }

     Console.ReadLine();
}

Upvotes: 1

Related Questions