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:
- 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
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:
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, 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.
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
{
public byte[] UserPhoto { get; set; }
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 BeginForm
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 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)
{
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;
[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);
}
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.
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.
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:
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.
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
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 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