Click here to Skip to main content
14,297,280 members

MVC ASP.NET Identity Customizing For Adding Profile Image

Rate this:
5.00 (13 votes)
Please Sign up or sign in to vote.
5.00 (13 votes)
19 Jun 2016CPOL
In this article, we will see in detail about using ASP.NET Identity in MVC Application.

Introduction

Image 1

  1. In our previous article wehave explained about how to 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 users Uploaded profile Image in home page and in Title bar.

Image 2

Prerequisites

Visual Studio 2015: You can download it from here.

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.

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

<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

public class ApplicationUser : IdentityUser
    {
        // Here we add a byte to Save the user Profile Pictuer
        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.

[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 begin 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>

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.

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

Image 11

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 to be displayed 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 upload and display part. Let’s start run 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

shanuMVCProfileImage.zip -  2016-06-08

License

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

Share

About the Author

syed shanu
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
memberMd 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.

Article
Posted 7 Jun 2016

Stats

19.6K views
738 downloads
23 bookmarked