ASP.NET Core 6.0 - Profile Image Control

This article describes the Profile Image Control with options to use an image file, webcam snapshot, or a stock image stored on the server. I will assume you have downloaded the ASP.NET Core 6.0 - Users With Comments Project.

Users With Comments Project and Article Series

The ASP.NET Core 6.0 - Users With Comments Project (UWCP) implements public member profiles and a moderated comment workflow from user submission to admin publication. I started with the ASP.NET Core 6.0 - Users With Device 2FA Project (UWD2FAP) which implements WebAuthn, also known as FIDO2, instead of authenticator apps. The latest version of the UWCP is published at Preview. KenHaggerty. Com. I encourage you to register and submit a comment. Details, screenshots, and related articles can be found at ASP.NET Core 6.0 - Users With Comments Project. The details page includes the version change log.

Visual Studio 2022 (VS 2022) is required to develop .NET 6 and ASP.NET Core 6.0 applications. .NET 6 and ASP.NET Core 6.0 are Long Term Support (LTS) releases and will be supported until November 08, 2024. .NET 5 is a Current release and will be supported until May 08, 2022. .NET 3.1 is a LTS release and will be supported until December 3, 2022. See .NET and .NET Core release lifecycle.

I wanted to encourage users to use a profile image. I had already implemented Croppie to crop and resize a file image before it is uploaded and stored as a Data URL. I developed a ProfileImage API and a new Profile Image Control which adds options to use a webcam snapshot, or a stock image stored on the server.

I developed a ProfileImage API controller which implements GET, POST, and DELETE methods. The API Authorization article describes restricting access for these methods to the user or an authorized administrator. The POST and DELETE methods implement the ValidateAntiForgeryToken attribute to prevent Cross-Site Request Forgery (XSRF/CSRF) attacks.

ProfileImageController.cs:
...
[HttpPost]
[Route("Post")]
[ValidateAntiForgeryToken]
public async Task<JsonResult> PostAsync(ProfileImagePostBodyModel model)
...

The partial view injects IAntiforgery to generate a RequestToken.

_ProfileImagePartial.cshtml:
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery _antiforgery;
@{
    var requestToken = _antiforgery.GetAndStoreTokens(Context).RequestToken;
}
<input id="RequestVerificationToken" type="hidden" value="@requestToken" />
...

The postProfileImage and deleteProfileImage JavaScript functions include the RequestToken in a RequestVerificationToken header.

function postProfileImage() {
    let postData = { appUserId: imageAppUserId, imageString: previewImage.getAttribute('src')}; 
    return fetch('@($"{AppSettings.ProfileImageApiUrlBase}{AppSettings.ProfileImagePostRoute}")',
        {
            method: 'post', credentials: 'same-origin', headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                'RequestVerificationToken': document.querySelector('#RequestVerificationToken').value },
            body: JSON.stringify(postData)
        })
        .then(function (response) { if (response.ok) return response.text(); else throw Error('Response Not OK'); })
        .then(function(text) { try { return JSON.parse(text); } catch (err) { throw Error(err); } })
        .then(function (responseJSON) {
            console.log(JSON.stringify(responseJSON));
            if (responseJSON.Status == 'Success') {
                document.querySelector('.current-image').setAttribute('src', responseJSON.CurrentImageString);
                removeImageButton.classList.remove('d-none');
                clearStockImageSelected();
                setImageCrop();
                clearCaptureImageSelected();
            } else showMessageModal(responseJSON.Errors, 'alert-danger');
        }).catch(function (error) { showMessageModal(error, 'alert-danger'); })
}

The partial view implements Bootstrap Tabs and AppSettings.cs implements properties to enable the Stock, File/Crop, and Webcam/Capture features.

public static class AppSettings
{
...
    /// <summary>
    /// Enables the stock image feature.
    /// </summary>
    public static readonly bool ProfileImageStockEnabled = true;
    /// <summary>
    /// Enables the upload image file feature.
    /// </summary>
    public static readonly bool ProfileImageCropEnabled = true;
    /// <summary>
    /// Enables the webcam image feature.
    /// </summary>
    public static readonly bool ProfileImageCaptureEnabled = true;
...

The File/Crop feature allows the user to crop and resize a file image before it is uploaded.

Croppie Choose Picture.
Croppie Cropped Picture.

The Stock feature allows the user to select an image which is a stored file on the server.

Stock Select.
Stock Select Mobile.

The Webcam/Capture feature allows the user to capture an image with a webcam.

Webcam Capture.
Webcam Capture Mobile.
Ken Haggerty
Created 06/08/22
Updated 06/19/22 15:23 GMT

Log In or Reset Quota to read more.

Successfully completed. Thank you for contributing.
Processing...
Something went wrong. Please try again.
Contribute to enjoy content without advertisments.
You can contribute without registering.

Comments(0)

Loading...
Loading...

Not accepting new comments.

Submit your comment. Comments are moderated.

User Image.
DisplayedName - Member Since ?