在我的应用程序中,我想在布局页面(_LoginPartial)中显示用户个人资料图片。
在AspNet Identity
成员资格中,他们是AspNerUser
表。我想自定义此AspNerUser
表以维护图像字段。
然后在布局页面(_LoginPartial
)视图中显示该图像。
我该怎么做?真的很感激可以建议一种方法来做到这一点
修改
我使用ADO.NET实体模型生成了我的DataBaseContext名称,数据库上下文名称为ProjectNameEntities
然后我尝试在PMC上使用以下命令启用迁移
Enable-Migrations -ContextTypeName myProject.Models.ProjectNameEntities
但后来我遇到了错误
创建DbModelBuilder或从创建的DbContext编写EDMX 不支持使用Database First或Model First。 EDMX只能是 从不使用现有的Code First DbContext获得 DbCompiledModel。
这可能与edmx模型有关吗?
答案 0 :(得分:13)
您需要做的第一件事是修改构建数据库表的ApplicationUser Model。该类通常位于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
中,将以下调用添加到我们刚刚创建的Action中,以便显示图像。您需要将控制器名称更改为您执行操作的控制器。
<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,看起来有一个表格如下:(请注意,根据您的项目结构,操作和控制器位置可能会有所不同)
@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