Click here to Skip to main content
15,877,572 members
Articles / Web Development / HTML

MVC ASP.NET Identity Customizing for Adding Profile Image

Rate me:
Please Sign up or sign in to vote.
5.00/5 (13 votes)
19 Jun 2016CPOL4 min read 31.9K   841   23   4
In this article, we will see in detail about using ASP.NET Identity in MVC application.

Image 1

Introduction

In our previous article, we have explained how to customize 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 users Uploaded profile Image in home page and in Title bar

Image 2

Prerequisite

Using the Code

Step 1: Creating 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:

SQL
---- =============================================                             
---- 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 our Visual Studio 2015, click Start, then Programs and select Visual Studio 2015 - Click 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.

Image 3

Step 3: Web.Config

In 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.

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

XML
<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 database. Now, here in ApplicationUser class, we will be adding a new property to store the image. Here, we declare the property type as byte like below:

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

Image 4

Step 5: MVC Model Part

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

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

Image 5

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 BeginForm like below:

Razor
@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.

HTML
<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>

Image 6

Step 7: MVC Controller Part

Image 7

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.

C#
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);
                    
                  
                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

So 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 home page and in 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 menu bar.

Create FileContentResult method in Home controller as UserPhotos to display the image in home page and in Menu bar.

Image 8

In 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 I will display the default image as “?” like below. Here, we display the image in both top menu and in home page.

Image 9

If the user is authenticated and successfully logged in to our system, then we display the logged in user profile picture in home page like below:

Image 10

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

C#
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

Image 11

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

HTML
<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 to be displayed at the top of our page, we write the below code in _Layout.cshtml:

HTML
<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 new user with Image and check for output.

Points of Interest

Firstly, create a sample UserProfileDB database in your SQL Server. In the Web.Config file, change the DefaultConnection connection string with your SQL Server Connections and run the application.

History

  • 8th June, 2016: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
QuestionGood to se u Pin
Md Ghouse22-Nov-16 19:10
Md Ghouse22-Nov-16 19:10 
AnswerRe: Good to se u Pin
syed shanu22-Nov-16 20:41
mvasyed shanu22-Nov-16 20:41 
GeneralMy vote of 5 Pin
Santhakumar M7-Jun-16 21:55
professionalSanthakumar M7-Jun-16 21:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.