Introduction
Prerequisites
- 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
-
-
-
- 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 -> Programs-> Visual Studio 2015-> Visual Studio 2015.
New-> Project-> Web -> ASP.NET Web Application. Enter your project name and click OK.
Select MVC and click OK.
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>
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 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
- {
-
- public byte[] UserPhoto { get; set; }
- //We can find this class inside the In IdentityModels.cs in Model folder
Step 5: MVC Model Part.
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.
First we add
, enctype = "multipart/form-data" in begin form, as shown 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 to upload 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,
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 is to be saved in our users table.
- if (ModelState.IsValid) {
-
-
- 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
- };
-
-
- 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)
- {
-
-
- 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 };
-
-
- 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);
- }
-
-
- return View(model);
- }
Now, we have successfully completed the Image uploading part to
AspNetUsers Table in our local SQL Server Database.
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 Home Controller, we create a method named as
UserPhotos and return the image to View page for the 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 his default image as “?”, as shown below. Here, we display the image both at top menu and on home page.
If the user is authenticated and successfully logged in to our system then we display the logged in user profile picture on the home page, as shown below:
This is the complete code to check the Authenticated user and return the valid user’s image to our View page .This is the method that 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");
-
- }
-
- 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 code shown below 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 run our application and register new user with image and check for output.