I have a web application which displays teams messages from various channels in one place, when a user sends an image in teams chat, it is received as a url in the format
https://graph.microsoft.com/beta/teams/dca91067-20f9-485e-82aa-5e38NGDJKF4/channels/19:[email protected]/messages/1715097164087/hostedContents/aBDhbhfhbLWN1cv/$value/”
If you try to access this url, it will say authentication is needed, therefore I detect every time a user sends a message containing urls in this format, then call the following function:
public async Task<string> GetImageAsBase64(ILogger<TeamsHostedService> logger, string url)
{
AuthenticationHelper helper = new AuthenticationHelper(logger);
var token = await helper.GetTokenForAppAsync();
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
try
{
var imageBytes = await httpClient.GetByteArrayAsync(url);
return Convert.ToBase64String(imageBytes);
}
catch (Exception ex)
{
logger.LogError("Failed to get image as base64 from URL: {0} | ExceptionType={1} | Message={2} | StackTrace={3} | InnerException={4}", url, ex.GetType(), ex.Message, ex.StackTrace, ex.InnerException);
return "";
}
}
}
This code mostly works, but I often see that images are not displaying in the web page, and for these cases there is an HttpRequestException with status code 429 (too many requests) occurring on the line
var imageBytes = await httpClient.GetByteArrayAsync(url);
Is there a better way to access many images in various teams chats using microsoft graph?
Any help is appreciated, thank you for your support!
I’ve tried multiple retry attempts and increased the time between calls for a particular url to 90 seconds, after 3 retries it will return an empty string and log an error. Some retries work, others do not.
traveling-waffles is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.