Showing a User Avatar on a Kentico MVC site

By on

Avatar image

When working with a Kentico MVC web site I encountered an unexprcted problem. How can I display the user's avatar image on the MVC site?
The avatar is stored in the administration site as part of the user's profile. As opposed to media galleries, that have their images synchronized between the administration site and the MVC site using a web farm setting, the avatar image resides on the administration site only. This poses a problem: how can we display the avatar image on the MVC site when the file is not really there?

The solution: The Kentico API.
Thankfully the Kentico API exposes a method for reading a UserInfo's avatar binary data. See the following example from a Razor view:

@{
    if (Model.Article.Author.UserAvatarID > 0)
    {
        var base64 = Convert.ToBase64String(CMS.Membership.AvatarInfoProvider.GetAvatarInfo(Model.Article.Author.UserAvatarID)?.GetBinaryData());
        var imgSrc = String.Format("data:image/jpeg;base64,{0}", base64);

        <img src="@imgSrc" alt="@Model.Article.Author.FullName">
    }
}

The Author property in the example is a UserInfo object. We can use it to call the GetAvatarInfo method and then call the GetBinaryData method. The binary data needs to be converted to a base 64 string, and then it can be placed as image content inside an <img> tag in the HTML.

The avatar you see at the end of this blog post is an example of the result!


 

Noam Rinat

About the Author

Noam Rinat