Forum Discussion
How to get user photo in C# using Graph API?
- Nov 21, 2017
I found the solution to this issue in one of the Richard diZerega's sample bots. Following is the way you display the user's photo in bot.
Get the byte array of the user's photo by using Graph API.
// Extension method public static async Task<byte[]> GetStreamWithAuthAsync(this HttpClient client, string accessToken, string endpoint) { client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken); client.DefaultRequestHeaders.Add("Accept", "application/json"); using (var response = await client.GetAsync(endpoint)) { if (response.IsSuccessStatusCode) { var stream = await response.Content.ReadAsStreamAsync(); byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, (int)stream.Length); return bytes; } else return null; } }
Assign the above byte array with the prefix "data:image/png;base64," and assign it to image URL property.
// Get the users profile photo from the Microsoft Graph var bytes = await new HttpClient().GetStreamWithAuthAsync(token, "https://graph.microsoft.com/v1.0/me/photo/$value"); var pic = "data:image/png;base64," + Convert.ToBase64String(bytes); ThumbnailCard card = new ThumbnailCard() { Title = $"{((JValue)jItem["Subject"]).Value}", Subtitle = jItem.SelectToken("sender.emailAdress.name").ToString(), Text = jItem.SelectToken("body.content").ToString(), Images = new List<CardImage>() { new CardImage() { Url= pic } } }; return card;
I found the solution to this issue in one of the Richard diZerega's sample bots. Following is the way you display the user's photo in bot.
Get the byte array of the user's photo by using Graph API.
// Extension method public static async Task<byte[]> GetStreamWithAuthAsync(this HttpClient client, string accessToken, string endpoint) { client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken); client.DefaultRequestHeaders.Add("Accept", "application/json"); using (var response = await client.GetAsync(endpoint)) { if (response.IsSuccessStatusCode) { var stream = await response.Content.ReadAsStreamAsync(); byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, (int)stream.Length); return bytes; } else return null; } }
Assign the above byte array with the prefix "data:image/png;base64," and assign it to image URL property.
// Get the users profile photo from the Microsoft Graph var bytes = await new HttpClient().GetStreamWithAuthAsync(token, "https://graph.microsoft.com/v1.0/me/photo/$value"); var pic = "data:image/png;base64," + Convert.ToBase64String(bytes); ThumbnailCard card = new ThumbnailCard() { Title = $"{((JValue)jItem["Subject"]).Value}", Subtitle = jItem.SelectToken("sender.emailAdress.name").ToString(), Text = jItem.SelectToken("body.content").ToString(), Images = new List<CardImage>() { new CardImage() { Url= pic } } }; return card;
How would you do this for a single page web app using PHP or MSAL.js
I can get the details data, but not the actual photo