How do I avoid rate limit issue when extracting many images from microsoft graph urls?

Siddiqui, Wasif 0 Reputation points
2024-07-11T17:05:40.2233333+00:00

Hi support, 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:Ub3dsjnsjjrVvkwYYapk3AIfQatftFaxBY01@thread.tacv2/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);

I am thinking the server which hosts these images may have some limit to how many images I can authenticate and convert.

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!

Microsoft Teams
Microsoft Teams
A Microsoft customizable chat-based workspace.
10,088 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,553 questions
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,002 questions
Microsoft Teams Development
Microsoft Teams Development
Microsoft Teams: A Microsoft customizable chat-based workspace.Development: The process of researching, productizing, and refining new or existing technologies.
3,250 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.