asp.net-core-mvcmicrosoft-graph-sdks

Microsoft Graph User Photo 'UnknownError'


When I browse to: 'Home/GetProfilePhoto?userPrincipalName=MyUserPrincipalName@mydomain.com' I get a 'UnknownError"

HomeController.cs

[AuthorizeForScopes(Scopes = new[] { "User.Read.All" })]
public async Task<IActionResult> GetProfilePhoto(string urserPrincipleName)
{
    var photo = await _graphServiceClient.Users["{urserPrincipleName}"].Photo.Content.Request().GetAsync();

    return PartialView("_Headshot", photo);
}

_Headshot.cshtml

@model Stream
<img src="data:image/jpg;base64, @Model.NotSureHowToGetAllBytesFromStreamHere" />

Solution

    1. "UnknownError":

    The parameter name of the method is urserPrincipleName, and the query string in the URL is ?userPrincipalName, you should make sure that the parameter name matches exactly with what you're expecting in the query string.

    And the .Users["{urserPrincipleName}"] is a placeholder, where userPrincipalName is passed as a method parameter. So, you should change it to .Users[userPrincipalName].

    [AuthorizeForScopes(Scopes = new[] { "User.Read.All" })]
    // 1. change the parameter here
    public async Task<IActionResult> GetProfilePhoto(string userPrincipalName)
    {
        // 2. change the placeholder to parameter here
        var photo = await _graphServiceClient.Users[userPrincipalName].Photo.Content.Request().GetAsync();
    
        return PartialView("_Headshot", photo);
    }
    
    1. @Model.NotSureHowToGetAllBytesFromStreamHere:

    You should convert the Stream to a Base64-encoded string:

    @model Stream
    @{
        // Read all bytes from the Stream
        byte[] bytes;
        using (var memoryStream = new MemoryStream())
        {
            Model.CopyTo(memoryStream);
            bytes = memoryStream.ToArray();
        }
    
        // Convert bytes to Base64 string
        string base64String = Convert.ToBase64String(bytes);
    }
    
    <h3>show Image:</h3>
    <!-- Display the image using Base64 string -->
    <img src="data:image/jpeg;base64, @base64String" />