Receiving Images to Your Skype Botframework Bot (v2!)

If you’re getting a “403” HTTP error when attempting to receive an image sent to your Skype bot, and the previous use of message.ServiceUrl to create a ConnectorClient didn’t work, try this more verbose version which explicitly sets the authorization header:

byte[] data;

if (image.ContentUrl != null)
{
    using (var connectorClient 
        = new ConnectorClient(new Uri(message.ServiceUrl)))
    {
        var token = 
            await (connectorClient.Credentials as MicrosoftAppCredentials)
                .GetTokenAsync();

        var uri = new Uri(image.ContentUrl);

        using (var httpClient = new HttpClient())
        {
            if (uri.Host.EndsWith("skype.com") 
                && uri.Scheme == Uri.UriSchemeHttps)
            {
                httpClient
                    .DefaultRequestHeaders
                    .Authorization = 
                        new AuthenticationHeaderValue("Bearer", token);

                httpClient
                    .DefaultRequestHeaders
                    .Accept
                    .Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
            }

            // Get the image in a byte[] variable
            data = await httpClient.GetByteArrayAsync(uri);
        }
    }
}