Skip to content

GetPhotoAsync throws exception when user has no profile photo #1860

@KunalParmar12

Description

@KunalParmar12

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.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions