Introduction- In our previous article, we have explained about how to customize ASP.NET MVC 5 Security and create user role and its 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,
- To upload and store User Profile Image to AspNetUsers table in SQL Server.
- Display the authenticated Logged in users, Uploaded profile Image in home page and in Title bar.

- Visual Studio 2015 - You can download it from here.
Using the code
Step 1: Create 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 script as shown below in your SQL Server to create a database.
- 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
After installing our Visual Studio 2015, click Start -> Programs-> Visual Studio 2015-> Visual Studio 2015.

Step 3: Web.Config
In web.config file, we can find the DefaultConnection 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>
In IdentityModels.cs, we need to add the image property to be used for storing our image to the database. In ApplicationUser class, we will be adding a new property to store the image and declare the property type as byte as shown below:
- public class ApplicationUser : IdentityUser
- {
- // Here we add a byte to Save the user Profile Pictuer
- public byte[] UserPhoto { get; set; }
- //We can find this class inside the In IdentityModels.cs in Model folder

In AccountViewModel.cs, check for the RegisterViewModel and add the properties as shown 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 code shown below to upload images to AspNetUsers table in our DB.
- @using(Html.BeginForm("Register", "Account", FormMethod.Post, new {
- @class = "form-horizontal", role = "form", enctype = "multipart/form-data"
- })) {
- <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>

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.
- 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;
- [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
- // Send an email with this link
- // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
- // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
- // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
- return RedirectToAction("Index", "Home");
- }
- AddErrors(result);
- }
- // If we got this far, something failed, redisplay form
- return View(model);
- }
We will see how to display the logged in user Image on the home page and in the menu bar.
Step 8: Display user image in the home page.
For displaying this, we create a FileContentResult Method to display the image on user home and on menu bar.
Create FileContentResult method in Home controller as UserPhotos are used to display the image in home page and on Menu bar.
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 his default image as “?”, as shown below. Here, we display the image both at top menu and on home page.


- 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");
- }
- }
Home view Page:

- <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>
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>
So now we have completed both upload and display part. Let’s run our application and register new user with image and check for output.

Ghoust BilaPosted Jul 15, 2020, 1:17 AM
Greetings Im getting this compilation error Severity Code Description Project File LineError CS7036 There is no argument given that corresponds to the required formal parameter 'key' of 'IOwinContext.Get<T>(string)'
Maria PrincePosted Mar 2, 2020, 7:20 AM
Thanks........
Nitesh yadaoPosted Aug 27, 2019, 4:56 AM
Hello, If error occurred while registering user, how to maintain profile image. now its gets remove we need to upload new one.
hachim hachimPosted Aug 23, 2019, 5:28 AM
Great job it is helpful for me ;Thank you Sir
DS DistributionPosted Apr 16, 2019, 2:39 AM
I had this error where submit System.FormatException: The entry is not a valid Base64 string, it contains a non-Base 64 character
Saravanan VPosted Mar 19, 2018, 8:03 PM
Nicely explained...
Isaac HolykPosted May 13, 2017, 9:42 PM
Could you please show how to change the profile picture once it has been added by adding a HTMLActionLink to the Index/Manage View, or something. I imagine users might want to change that picture at some point.
Syed ShanuPosted Jun 6, 2016, 9:20 PM
Thank You
Thennarasu NPosted Jun 6, 2016, 9:57 AM
Great Work Sir.it's helped Me lot Sir................
Sonu ChaudharyPosted Jun 6, 2016, 9:57 AM
good one...
Anu VPosted Jun 3, 2016, 7:23 AM
Nice
Manish Kumar ChoudharyPosted Jun 3, 2016, 1:05 AM
Nice one.
Humayun Kabir MamunPosted Jun 1, 2016, 2:12 AM
Good One...
Debasis SahaPosted Jun 1, 2016, 1:47 AM
Nice share..
Vignesh ManiPosted May 31, 2016, 4:16 PM
Nice
Ravi PatelPosted May 31, 2016, 4:48 AM
nice explanation, thanks sir
Thiruppathi RPosted May 31, 2016, 3:07 AM
Nice article...can make it as angularjs ..
Munesh SharmaPosted May 31, 2016, 12:16 AM
nice
Raja TPosted May 31, 2016, 12:14 AM
Good, Thansk for sharing