User avatars

Avatars are images associated with user accounts. They can be displayed, for example, on a user’s public profile. Avatars serves as graphical representations of users and are often used to personalize user contributions on websites.

Managing user avatars

Site users can manage avatars either in the administration interface or on the live site, depending on their privilege level:

  • Site administrators can change the avatar of any user:
    1. Open the Users application.
    2. Edit () a user and switch to the Settings tab.
    3. Change the user’s avatar in the User picture field.
      Changing a user’s avatar
  • Users with access to the administration interface can set their avatar in the My profile application on the Details tab.
  • Regular site users can upload or change their avatars after site developers implement avatar support on the live site. The steps required to change user avatars then depend entirely on the custom implementation. Typically on most websites, avatar management can be found in an “account management” section.

By default, newly created or registered users do not have an avatar associated with them in the system.

Limiting the size of avatar images

Site administrators can configure the maximum size for user-uploaded avatar images in the Settings application under Security & Membership -> Avatars. The system resizes all uploaded avatar images to fit these constraints. 

Working with user avatars on the live site

Before regular site users can use the avatar functionality, site developers need to implement support for displaying and manipulating user avatars.

The system provides the following API developers can leverage when implementing user avatar support on the live site (as part of the Kentico.Content.Web.Mvc namespace):

  • IAvatarService – service used to retrieve and update user avatars. It provides the following methods:
    • bool UpdateAvatar – sets or updates an existing avatar for the specified user. The avatar is bound to the user and cannot be selected by other users. When the users changes their avatar, their previous avatar is deleted from the system.

      When processing uploaded files, the UpdateAvatar method checks whether the extension of the uploaded file is included in the list of allowed extensions in Settings -> System -> Files -> Upload extensions and resizes the image to fit the dimensions configured in the avatar settings.

    • string GetAvatarUrl – returns an application relative virtual URL (starting with ~/) for the avatar of the specified user.

    • void DeleteAvatar – deletes the avatar image associated with the specified user.

  • Url.Kentico().AvatarUrl(string userName) – extension method for System.Web.Mvc.UrlHelper that returns the absolute URL of the avatar for the specified user. The method has the following optional parameters:
    • string pathToDefaultAvatar – relative path to a default avatar image displayed for users with no assigned avatar. For example, “~/Content/Images/default-avatar.png”.
    • int maxSideSize – constrains the avatar image so that its larger side’s dimension matches the entered value. Aspect ratio is preserved and the width and height settings are not applied. Note that the maximum avatar size is given by the avatar settings (i.e., the method does not upscale the image). The default avatar image is unaffected by this parameter.
    • int width, height – constrains the maximum width or height of the avatar image, respectively. Note that the maximum avatar size is always given by the avatar settings (i.e., the method does not upscale the image). The default avatar image is unaffected by these parameters.

The following set of examples demonstrates the usage of the avatar API on the live site.

Displaying user avatars

To display user avatars, call the Url.Kentico().AvatarUrl extension method in the code of your views. For example:

@using Kentico.Membership.Web.Mvc

@model Kentico.Membership.User


<img src="@Url.Kentico().AvatarUrl(Model.UserName, pathToDefaultAvatar: "~/Content/Images/default-avatar.png")" />


This snippet renders an img tag with the given user’s avatar. If the user has no avatar image assigned, it displays the image specified in the pathToDefaultAvatar parameter.

Implementing an avatar uploader

This section demonstrates the implementation of a simple avatar uploader. The uploader allows site users to change the avatar image associated with their account:

Tip: To view the full code of a functional example, you can inspect and download the LearningKit project on GitHub. You can also run the LearningKit website by connecting the project to a Xperience database. Follow the instructions in the repository’s README file.

  1. Initialize an instance of IAvatarService in the controller class used to manage user account activities on your website.

             private readonly IAvatarService avatarService;
             private readonly IEventLogService eventLogService;
             public AccountController(IAvatarService avatarService,
                                      IEventLogService eventLogService)
                 // Initializes an instance of a service used to manage user avatars
                 this.avatarService = avatarService;
                 this.eventLogService = eventLogService;
  2. Add a new action that handles uploaded avatars and assigns them to users.

             public ActionResult ChangeAvatar(HttpPostedFileBase avatarUpload)
                 object routevalues = null;
                 // Checks that the avatar file was uploaded
                 if (avatarUpload != null && avatarUpload.ContentLength > 0)
                     // Gets the representation of the user requesting avatar change from Xperience
                     var user = KenticoUserManager.FindByName(User.Identity.Name);
                     // Attempts to update the user's avatar
                     if (!avatarService.UpdateAvatar(avatarUpload.ToUploadedFile(), user.Id, SiteContext.CurrentSiteName))
                         // If the avatar update failed (e.g., the user uploaded an image with an usupported file extension)
                         // sets a flag for an error message in the corresponding view
                         routevalues = new { avatarUpdateFailed = true };
                 return RedirectToAction("EditUser", "Account", routevalues);

    The avatarUpdateFailed flag controls the display of an error message to the user in the corresponding view. It should be set to false by default in the controller action handling the uploader display (e.g., on the user account overview page):

     public ActionResult EditUser(bool avatarUpdateFailed = false)
         // Finds the user based on their current user name
         User user = KenticoUserManager.FindByName(User.Identity.Name);
         EditUserAccountViewModel model = new EditUserAccountViewModel() 
             User = user,
             AvatarUpdateFailed = avatarUpdateFailed
          return View(model);
  3. Update the corresponding view to render user avatars and add avatar update functionality. In this example, the form handling the avatar image submit is hidden and invoked when the user clicks on the Change avatar button. The submit() method call bound to the onchange event of the text box form input ensures the form is immediately submitted after a user selects an avatar using the browser’s file explorer.

     @using Kentico.Membership.Web.Mvc
         <h2>User Avatar</h2>
             @* Generates a link to a user's avatar (or a default one if specified and a user avatar is not found).
                 Note that the properties constraining avatar dimensions do not work for default avatars. *@
             <img src="@Url.Kentico().AvatarUrl(Model.User.UserName, maxSideSize: 500, width: 500, height: 500, pathToDefaultAvatar: " ~/Content/Images/default-avatar.png")" />
             <br />
                 <div onclick="document.getElementById('avatarUpload').click()">Change avatar</div>
         @* Displays an error message in case the user uploaded a file with an unsupported file extension.
             Supported file extensions can be configured in Settings -> System -> Files -> Upload extensions in the Administration interface. *@
         @if (Model.AvatarUpdateFailed)
                 <span>Please upload a valid image file.</span>
         @using (@Html.BeginForm("ChangeAvatar", "Account", FormMethod.Post, new { enctype = "multipart/form-data", id = "avatarUploadForm", style = "display:none;" }))
             // Generates a hidden field holding an anti-forgery token
             // The Xperience API version of this method ensures tokens are correctly generated for pages where output caching is enabled
             @Html.TextBox("avatarUpload", "", new { type = "file", id = "avatarUpload", accept = "image/*", onchange = "document.getElementById('avatarUploadForm').submit()" })

The site’s users can now change their avatars at will using the avatar uploader.

Deleting user avatars

To allow users to delete their avatars, create a controller action that calls the IAvatarService.DeleteAvatar method:

        public ActionResult DeleteAvatar(int userId)
            // Deletes the avatar image associated with the user

            return RedirectToAction("EditUser", "Account");

The method removes the avatar image from the user and deletes the associated avatar object from the system. You can then extend the view of the page where users manage their account, and add a HTML form that posts the user ID of the current user to the given action.