You can download the Source Code from this link Download Source Code.

Introduction

  1. In our previous article, we explained about customizing ASP.NET MVC 5 Security and Creating User Role and User Role base Menu Management (Dynamic menu using MVC and AngularJS)

In this article, we will see in detail about using ASP.NET Identity in MVC Application:

1)     To upload and store User Profile Image to AspNetUsers table in SQL Server.

2)     Display the authenticated Logged in user's uploaded profile image on the  homepage and title bar.

Building the Sample

Prerequisites

Visual Studio 2015: You can download it from here.

Code Part

Step 1: Creating The Database

First, we create a database to store all our ASP.NET Identity details to be stored in our Local SQL Server. Here we have used SQL Server 2014. Run the below script in your SQL Server to create a database.

---- =============================================                               
---- Author      : Shanu                             
---- Create date : 2016-05-30                               
---- Description : To Create Database     
---- Latest                               
---- Modifier    : Shanu                                
---- Modify date : 2016-05-30                   
---- =============================================  
----Script to create DB  
    
USE MASTER  
GO  
    
 --1) Check for the Database Exists .If the database is exist then drop and create new DB  
    
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'UserProfileDB' )  
DROP DATABASE UserProfileDB  
    
GO  
    
CREATE DATABASE UserProfileDB  
GO  
    
USE UserProfileDB  
GO

Step 2: Create your Web Application in Visual Studio 2015

After installing Visual Studio 2015, click Start, then Programs and select Visual Studio 2015. Click New, then Project, select Web, and then select ASP.NET Web Application. Enter your project name and click OK. Select MVC and click OK.  

Step 3: Web.Config


In the web.config file, we can find the DefaultConnection Connection string. By default, ASP.NET MVC will use this connection string to create all ASP.NET identity-related tables like AspNetUsers, etc. Here in connection string, we will be using our newly created DB name.

In connection string change your SQL Server Name, UID and PWD to create and store all user details in one database. 

<connectionStrings>  
    <add name="DefaultConnection" connectionString="data source=YOURSERVERNAME;initial catalog=UserProfileDB;user id=UID;password=PWD;Integrated Security=True" providerName="System.Data.SqlClient"  />   
 </connectionStrings>

Step 4: IdentityModels.cs

In IdentityModels.cs we need to add the image property to be used for storing our image to the database. In the ApplicationUser class we will be adding a new property to store the image. Declare the property type as byte like below:

public class ApplicationUser : IdentityUser
    {
        // Here we add a byte to Save the user Profile Picture
        public byte[] UserPhoto { get; set; }

We can find this class inside the In IdentityModels.cs in Model folder.

Step 5: MVC Model Part

Next in AccountViewModel.cs check for the RegisterViewModel and add the properties like below.

[Display(Name = "UserPhoto")]
        public byte[] UserPhoto { get; set; }

 

Step 6: Edit Register view to add our upload image

In Register.cshtml, we add the below code to upload images to AspNetUsers table in our DB.

First, we add enctype = "multipart/form-data" in beginning form like below.

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
{

Next, we need to customize our Register page to add the HTML Image Tag for uploading the image.

<div class="form-group">
        @Html.LabelFor(m => m.UserPhoto, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
             
            <input type="file" name="UserPhoto" id="fileUpload" accept=".png,.jpg,.jpeg,.gif,.tif" />
               
        </div>
    </div>

 Step 7: MVC Controller Part

Next in AccountController.cs we will update the code in the Register post method to customize and store the uploaded user image in ASP.NET identity database.

In the Register post method, we will save the uploaded image to the byte array and use this byte array result to be saved in our users table.

if (ModelState.IsValid)
            {
                   
                // To convert the user uploaded Photo as Byte Array before save to DB
                byte[] imageData = null;
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase poImgFile = Request.Files["UserPhoto"];
  
                    using (var binary = new BinaryReader(poImgFile.InputStream))
                    {
                        imageData = binary.ReadBytes(poImgFile.ContentLength);
                    }
                }
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
  
                //Here we pass the byte array to user context to store in db
                user.UserPhoto = imageData;

Here is the complete code of the Register post method.

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register([Bind(Exclude = "UserPhoto")]RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                   
                // To convert the user uploaded Photo as Byte Array before save to DB
                byte[] imageData = null;
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase poImgFile = Request.Files["UserPhoto"];
  
                    using (var binary = new BinaryReader(poImgFile.InputStream))
                    {
                        imageData = binary.ReadBytes(poImgFile.ContentLength);
                    }
                }
  
  
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
  
                //Here we pass the byte array to user context to store in db
                user.UserPhoto = imageData;
  
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                      
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 ;            
  
                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }
  
            // If we got this far, something failed, redisplay form
            return View(model);
        }

Now we have successfully completed the Image uploaded part to AspNetUsers Table in our local SQL Server Database.

Next, we will see how to display the logged in user Image on the homepage and in the menu bar. 

Step 8: Display User Image in home page

For displaying this we create a FileContentResult Method to display the image on user home and in the menu bar. 

Create FileContentResult method in Home controller as UserPhotos to display the image in the homepage and in the menu bar.

In the home controller, we create a method named as UserPhotos and return the image to View page for user profile display.

In this method, we check for Authenticated (Logged in) users. If the user is not logged In to our web application then display the default image as “?” like below. Here we display the image in both the top menu and homepage.

If the user is authenticated and successfully logged in to our system then we display the logged in user profile picture in the homepage like below.

Here is the complete code to check the Authenticated user and return the valid user’s image to our View page. This method we created in our Home controller.

public FileContentResult UserPhotos()
        {
            if (User.Identity.IsAuthenticated)
            {
            String    userId = User.Identity.GetUserId();
  
            if (userId == null)
                {
                    string fileName = HttpContext.Server.MapPath(@"~/Images/noImg.png");
  
                    byte[] imageData = null;
                    FileInfo fileInfo = new FileInfo(fileName);
                    long imageFileLength = fileInfo.Length;
                    FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                    BinaryReader br = new BinaryReader(fs);
                    imageData = br.ReadBytes((int)imageFileLength);
                      
                    return File(imageData, "image/png");
  
                }
              // to get the user details to load user Image
                var bdUsers = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
            var userImage = bdUsers.Users.Where(x => x.Id == userId).FirstOrDefault();
  
            return new FileContentResult(userImage.UserPhoto, "image/jpeg");
            }
            else
            {
                string fileName = HttpContext.Server.MapPath(@"~/Images/noImg.png");
  
                byte[] imageData = null;
                FileInfo fileInfo = new FileInfo(fileName);
                long imageFileLength = fileInfo.Length;
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                imageData = br.ReadBytes((int)imageFileLength);                 
                return File(imageData, "image/png");
                 
            }
        }

Step 9: MVC View Part

 Home view Page:

In Home Index View we write the below code to display our logged in users profile picture.

<h1>Shanu Profile Image ..
      
     <img src="@Url.Action("UserPhotos", "Home" )"  style="width:160px;height:160px; background: #FFFFFF;  
    margin: auto;
    -moz-border-radius: 60px;
    border-radius: 100px;
    padding: 6px;
    box-shadow: 0px 0px 20px #888;" />
    </h1>

_Layout.cshtml

To display our logged in user profile picture at the top of our page, we write the below code in _Layout.cshtml

<div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li
                        <img src="@Url.Action("UserPhotos", "Home" )" height="48" width="48" />
                    
                    </li>
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>

Step 10: Run The Application

So now we have completed both the upload and display part. Let’s start running our application and register a new user with image to check for output.

You can download the Source Code from this link Download Source Code

 

Next in AccountController.cs we will update the code in Register post method to customize and store the uploaded user image in ASP.NET identity database.

In the Register post method we will save the uploaded image to the byte array and use this byte array result to be saved in our users table.

 

Next in AccountController.cs we will update the code in Register post method to customize and store the uploaded user image in ASP.NET identity database.

In the Register post method we will save the uploaded image to the byte array and use this byte array result to be saved in our users table.