65.9K
CodeProject 正在变化。 阅读更多。
Home

MVC ASP.NET Identity 自定义添加个人资料图片

starIconstarIconstarIconstarIconstarIcon

5.00/5 (12投票s)

2016 年 6 月 7 日

CPOL

4分钟阅读

viewsIcon

36155

downloadIcon

875

在本文中,我们将详细介绍如何在 MVC 应用程序中使用 ASP.NET Identity。

引言

在我们之前的文章中,我们解释了如何自定义 ASP.NET MVC 5 安全和用户角色创建 以及 基于用户角色的菜单管理(使用 MVC 和 AngularJS 的动态菜单)

在本文中,我们将详细介绍如何在 MVC 应用程序中使用 ASP.NET Identity。

  1. 上传并存储用户个人资料图片到 SQL Server 的 AspNetUsers 表中。
  2. 在主页和标题栏中显示已认证的登录用户的上传的个人资料图片。

先决条件

Using the Code

步骤 1:创建数据库

首先,我们创建一个数据库来存储我们在本地 SQL Server 中需要存储的所有 ASP.NET Identity 详细信息。这里我们使用了 SQL Server 2014。在您的 SQL Server 中运行以下脚本来创建数据库。

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

步骤 2:在 Visual Studio 2015 中创建您的 Web 应用程序

安装我们的 Visual Studio 2015 后,点击 开始,然后点击 程序,选择 Visual Studio 2015 - 点击 Visual Studio 2015。点击 新建,然后点击 项目,选择 Web,然后选择 ASP.NET Web 应用程序。输入您的项目名称,然后点击 确定。选择 MVC,然后点击 确定

步骤 3:Web.Config

web.config 文件中,我们可以找到 DefaultConnection 连接字符串。默认情况下,ASP.NET MVC 将使用此连接字符串来创建所有 ASP.NET Identity 相关的表,例如 AspNetUsers 等。在这里,我们在连接字符串中使用我们新创建的数据库名称。

在这里,在连接字符串中,更改您的 SQL Server 名称、UID 和 PWD,以便在一个数据库中创建和存储所有用户详细信息。

<connectionStrings>  
    <add name="DefaultConnection" connectionString="data source=YOURSERVERNAME;
     initial catalog=UserProfileDB;user id=UID;password=PWD;Integrated Security=True" 
     providerName="System.Data.SqlClient"  />   
 </connectionStrings>

步骤 4:IdentityModels.cs

IdentityModels.cs 中,我们需要添加 image 属性来用于将我们的图片存储到数据库。现在,在这里的 ApplicationUser 类中,我们将添加一个新的属性来存储图片。这里,我们声明属性类型为 byte,如下所示:

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

步骤 5:MVC 模型部分

接下来,在 AccountViewModel.cs 中,检查 RegisterViewModel 并添加如下属性:

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

步骤 6:编辑注册视图以添加我们的上传图片

Register.cshtml 中,我们添加以下代码以上传图片到我们数据库的 AspNetUsers 表。

首先,我们在 BeginForm 中添加 enctype = "multipart/form-data",如下所示:

@using (Html.BeginForm("Register", "Account", FormMethod.Post, 
new { @class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))

接下来,我们需要自定义我们的 Register 页面,以添加 HTML 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>

步骤 7:MVC 控制器部分

接下来在 AccountController.cs 中,我们将更新 Register post 方法中的代码,以自定义并存储上传的用户图片到 ASP.NET Identity 数据库。

Register post 方法中,我们将把上传的图片保存到字节数组中,并使用此字节数组结果保存到我们的 users 表中。

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);
        }

现在,我们已经成功完成了将图片上传到我们本地 SQL Server 数据库的 AspNetUsers 表部分。

接下来,我们将看到如何在主页和菜单栏中显示登录用户的图片。

步骤 8:在主页显示用户图片

为了显示此功能,我们创建了一个 FileContentResult 方法来在用户主页和菜单栏中显示图片。

在 Home 控制器中创建一个名为 UserPhotosFileContentResult 方法,用于在主页和菜单栏中显示图片。

在 Home 控制器中,我们创建一个名为 UserPhotos 的方法,并将图片返回到 View 页面以供用户个人资料显示。

在此方法中,我们检查是否为已认证(已登录)的用户。如果用户未登录我们的 Web 应用程序,我将显示默认图片“?”,如下所示。在这里,我们在顶部菜单和主页中都显示图片。

如果用户已认证并成功登录到我们的系统,我们将显示登录用户的个人资料图片在主页上,如下所示:

这是检查已认证用户并向我们的 View 页面返回有效用户图片的完整代码。我们已将此方法创建在我们的 Home 控制器中。

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");      
            }
        }

步骤 9:MVC 视图部分

在 Home Index 视图中,我们编写以下代码来显示我们登录用户的个人资料图片。

<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

为了在我们页面的顶部显示登录用户的个人资料图片,我们在 _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>

步骤 10:运行应用程序

现在,我们已经完成了上传和显示部分。让我们开始运行我们的应用程序,注册带有图片的新用户,并检查输出。

关注点

首先,在您的 SQL Server 中创建一个名为 UserProfileDB 的示例数据库。在 Web.Config 文件中,更改 DefaultConnection 连接字符串为您的 SQL Server 连接,然后运行应用程序。

历史

  • 2016 年 6 月 8 日:初始版本
© . All rights reserved.