添加字段模型(代码优先)
您需要做的第一件事是修改构建数据库表的 ApplicationUser 模型。该类通常位于IdentityModels.cs 文件中。添加一个新字段来保存图像:
public class ApplicationUser : IdentityUser
{
// maybe be other code in this model
public byte[] ProfilePicture { get; set; }
}
接下来,您需要更新数据库以反映更改(假设您使用 Code First)。您可以在this article找到有关该过程的详细信息。
Enable-Migration
Add-Migration "Added user profile"
Update-Database (will apply any pending migrations to the database)
返回头像
现在向控制器添加一个动作,类似于:
public FileContentResult Photo(string userId)
{
// get EF Database (maybe different way in your applicaiton)
var db = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
// find the user. I am skipping validations and other checks.
var user = db.Users.Where(x => x.Id == userId).FirstOrDefault();
return new FileContentResult(user.ProfilePicture, "image/jpeg");
}
最后,在您的_LoginPartial 中,将以下调用添加到我们刚刚创建的操作中,只要您希望图像显示在任何地方。您需要将控制器名称更改为您执行操作的任何控制器。
<img src="@Url.Action("Photo", "Account" , new { UserId=User.Identity.GetUserId() })" />
保存头像
首先您需要创建一个页面来上传图片。创建一个动作来返回表单:
[HttpGet]
public ActionResult Profile()
{
ViewBag.Message = "Update your profile";
return View();
}
Razor 视图将被称为 Profile.cshtml,并且看起来上面有一个如下所示的表单:(请注意,根据您的项目结构,Action 和控制器的位置可能会有所不同)
@using (Html.BeginForm("Profile", "Manage", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<fieldset>
<legend>Photo</legend>
<div class="editor-label">
<label for="profile">FileName:</label>
</div>
<div class="editor-field">
<input name="Profile" id="profile" type="file" />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
表单将返回到一个动作,因此您需要创建一个如下所示的表单:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Profile(HttpPostedFileBase Profile)
{
// get EF Database (maybe different way in your applicaiton)
var db = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
// find the user. I am skipping validations and other checks.
var userid = User.Identity.GetUserId();
var user = db.Users.Where(x => x.Id == userid).FirstOrDefault();
// convert image stream to byte array
byte[] image = new byte[Profile.ContentLength];
Profile.InputStream.Read(image, 0, Convert.ToInt32(Profile.ContentLength));
user.ProfilePicture = image;
// save changes to database
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
请注意,需要根据您的规则进行验证和检查,但这是其工作原理的基本理念。
创建了一个 GitHub 项目,在工作示例中展示了上述基础知识:https://github.com/jsturtevant/mvc-aspnet-identity2-profile-picture-sample