Gaurav Barman Gaurav Barman - 1 year ago 128
C# Question

Getting 403 (Forbidden), Microsoft Bot is trying to make a Web Client - download data call

I am trying to create a bot using Microsoft


The issue I am facing is when the bot code is trying to download data(image which is uploaded by user to the bot) via any channel like Facebook messenger/Skype/Slack. The code to download is by creating a WebClient and making a DownloadData call by passing the attachment URL.

I am able to browse the uploaded image URL. Also, the code for download data via web client works fine if I write a console application rather than a Bot application.

c# Code snippet

WebClient wc = new WebClient();
byte[] bytes = wc.DownloadData(imageUrl); // This line gives 403 error

Kindly suggest what should be the solution for this issue.

Answer Source

Here is the complete fix for the issue:

    private async Task<IEnumerable<byte[]>> GetAttachmentsAsByteArrayAsync(Activity activity)
        var attachments = activity?.Attachments?
        .Where(attachment => attachment.ContentUrl != null)
        .Select(c => Tuple.Create(c.ContentType, c.ContentUrl));
        if (attachments != null && attachments.Any())
            var contentBytes = new List<byte[]>();
            using (var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl)))
                var token = await (connectorClient.Credentials as MicrosoftAppCredentials).GetTokenAsync();
                foreach (var content in attachments)
                    var uri = new Uri(content.Item2);
                    using (var httpClient = new HttpClient())
                        if (uri.Host.EndsWith("") && uri.Scheme == "https")
                            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
                            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(content.Item1));
                        contentBytes.Add(await httpClient.GetByteArrayAsync(uri));
            return contentBytes;
        return null;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download