繁体   English   中英

在 ASP.Net Identity (MVC) 中“注册”期间保存其他配置文件数据

[英]Save additional profile data during "Register" in ASP.Net Identity (MVC)

我需要在用户注册期间存储其他信息,例如:名字、姓氏等。

我的问题有两个部分:

  1. 如何在注册期间保存我的附加信息?
  2. 我当前的方法抛出错误:

一个或多个实体的验证失败。 有关更多详细信息,请参阅“EntityValidationErrors”属性 我已经在 VS 中检查了“Watch”,也使用了 try-catch 但它没有帮助。

在此先感谢您的帮助!


IdentityModels.cs

public class ApplicationIdentityAccount : IdentityUser
{
  public virtual ICollection<AccountProfile> AccountProfiles { get; set; }
}


public class AccountProfile
{


      [Key]
      public string AccountProfileID { get; set; }


      [DisplayName("First Name")]
      [StringLength(50)]
      [Required(ErrorMessage = "First name is required")]
      public string FirstName { get; set; }


      [DisplayName("Middle Name")]
      [StringLength(50)]
      public string MiddleName { get; set; }


      [DisplayName("Last Name")]
      [StringLength(50)]
      [Required(ErrorMessage = "Last name is required")]
      public string LastName { get; set; }

      public string UserId { get; set; }
      [ForeignKey("UserId")]
      public virtual ApplicationIdentityAccount User { get; set; }

}


public class ApplicationIdentityDbContext : IdentityDbContext<ApplicationIdentityAccount>
  {
 public ApplicationIdentityDbContext()
 : base("ApplicationIdentity", throwIfV1Schema: false)
  {
  }


    public static ApplicationIdentityDbContext Create()
      {
      return new ApplicationIdentityDbContext();
      }



public System.Data.Entity.DbSet<AccountProfile> AccountProfile { get; set; }

 }

AccountViewModels.cs > 注册视图模型

 public class RegisterViewModel
    {

    [Required]
    [Display(Name = "Username")]
    public string UserName { get; set; }

    [Required]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { 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; }
}

账户控制器.cs

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
      {
         if (ModelState.IsValid)
              {
               var user = new ApplicationIdentityAccount
                {
                   UserName = model.UserName,
                   Email = model.Email,
                   AccountProfile = new[] {new AccountProfile()
                {
                    FirstName = model.FirstName,
                    LastName = model.LastName
                }}
                };

             var result = await UserManager.CreateAsync(user, model.Password);


             if (result.Succeeded)
                {

               await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                        return RedirectToAction("Index", "Home");
                    }
                    AddErrors(result);
                    }


                // If we got this far, something failed, redisplay form
                return View(model);
    }

我知道我应该把FirstNameLastName放在里面:

var user = new ApplicationIdentityAccount
                    {
                       UserName = model.UserName,
                       Email = model.Email,
                    };

由于您的问题有两个部分:

  1. 您存储附加信息的方法是正确的
  2. 除非您看到实际错误,否则您无法继续,为了查看您需要在创建用户的位置添加它的详细信息。

     public override int SaveChanges() { try { return base.SaveChanges(); } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM