首页 > C# User.Identity自定义(登录信息自定义)

C# User.Identity自定义(登录信息自定义)

User.Identity只存了id和名字,怎么拓展 MVC 5


如果你想加入例如 Email ,
1.先去 \Models\ApplicationUser.cs 改:

public class ApplicationUser : IdentityUser
{
    public string Email { get; set; }
}

2.去 \ViewModels\Account\RegisterViewModel.cs

public class RegisterViewModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }
 
    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }
 
    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
 
    [Required]
    [Display(Name = "Email address")]
    public string Email { get; set; } 

3.\Views\Account\Register.cshtml 加上

<div class="form-group">
     @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
     <div class="col-md-10">
         @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
     </div>
</div>

4.那麼你可以在任何一個 Controller 內加上, 如在 About:

public ActionResult About()
{
    ViewBag.Message = "Your application description page.";
    UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));         
    var user = UserManager.FindById(User.Identity.GetUserId());
    if (user != null)
        ViewBag.Email = user.Email;
    else
        ViewBag.Email = "User not found.";
 
    return View();
}
【热门文章】
【热门文章】