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

时间:2015-10-18 18:32:33

标签: c# asp.net asp.net-mvc asp.net-identity

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

我的问题分为两部分:

  1. 如何在注册期间保存其他信息?
  2. 我当前的方法抛出错误:
  3. 一个或多个实体的验证失败。有关详细信息,请参阅“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&gt; RegisterViewModel

     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; }
    }
    

    AccountController.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 个答案:

答案 0 :(得分:1)

由于您的问题分为两部分:

  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);
        }
    }