-
Notifications
You must be signed in to change notification settings - Fork 906
Description
Description
The GetPhotoAsync method throws an exception when the signed-in user does not have a profile photo.
graphClient.Me.Photo.Content.GetAsync() fails (typically with a 404 / ServiceException), which causes the application to crash if not explicitly handled.
This scenario is common and should be handled gracefully.
Current Code
public async Task<string> GetPhotoAsync()
{
var graphClient = GetAuthenticatedClient();
var photo = await graphClient.Me.Photo.Content.GetAsync();
if (photo != null)
{
using var ms = new MemoryStream();
await photo.CopyToAsync(ms);
var buffers = ms.ToArray();
return $"data:image/png;base64,{Convert.ToBase64String(buffers)}";
}
return string.Empty;
}
Problem
If the user does not have a profile photo, GetAsync() throws an exception.
There is no exception handling, so the caller must handle this every time.
This leads to unnecessary crashes for a valid and expected scenario.
Expected Behavior
If the user does not have a profile photo, the method should:
Return an empty string (or null)
Not throw an exception
Suggested Fix (Recommended)
Catch ServiceException and explicitly handle the 404 Not Found case.
using Microsoft.Graph;
using System.Net;
public async Task<string> GetPhotoAsync()
{
try
{
var graphClient = GetAuthenticatedClient();
var photo = await graphClient.Me.Photo.Content.GetAsync();
if (photo == null)
return string.Empty;
using var ms = new MemoryStream();
await photo.CopyToAsync(ms);
return $"data:image/png;base64,{Convert.ToBase64String(ms.ToArray())}";
}
catch (ServiceException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
// User does not have a profile photo
return string.Empty;
}
}
Why This Approach
Avoids swallowing all exceptions with a generic catch (Exception)
Handles a known, expected condition explicitly
Makes the method safer and easier to consume
Additional Notes
This behavior is documented in Microsoft Graph:
/me/photo returns 404 Not Found when no profile photo exists.
Handling this inside the helper method improves developer experience and avoids repetitive error handling across the application.