我是ASP.NET MVC 5
上的newbby,我需要修改Identity membership
提供的用户表,为用户添加avatr。这样做有什么好处。谢谢
答案 0 :(得分:3)
很简单,您需要在ApplicationUser类中添加字段:
public class ApplicationUser : IdentityUser
{
public string Avatar { get; set; }
}
然后你可以编写一个扩展方法来访问用户的头像:
public static string GetAvatar(this System.Security.Principal.IIdentity user)
{
// Get user's avatar
//....
}
然后你可以这样使用:
<img class="img-circle" src="~/Content/Images/UserPhotos/@User.Identity.GetAvatar()" alt="profile">
用于添加照片的更新:您需要在视图中添加文件输入标记:
@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
@Html.LabelFor(m => m.Avatar, new { @class = "col-md-2 control-label" })
<div class="col-md-4">
<input type="file" name="file" value="" />
@Html.ValidationMessageFor(model => model.Avatar)
</div>
</div>
// Other fields
}
行动方法:
[HttpPost]
public async Task<ActionResult> ActionName(RegisterViewModel model, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
var fileName = UploadPhoto(file);
var user = new ApplicationUser
{
Avatar = fileName,
// Other fields
};
}
// code....
return View();
}
上传照片方法:
public string UploadPhoto(HttpPostedFileBase file)
{
if (file != null)
{
var fileName = Path.GetFileName(file.FileName);
var rondom = Guid.NewGuid() + fileName;
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/Images/UserPhotos"), rondom);
var filePathToSave = "UserPhotos/" + fileName;
if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/Content/Images/UserPhotos")))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Content/Images/UserPhotos"));
}
file.SaveAs(path);
return rondom;
}
return "nofile.png";
}