在&QUOT保存附加状态数据;注册"在ASP.Net身份(MVC) [英] Save additional profile data during "Register" in ASP.Net Identity (MVC)

查看:117
本文介绍了在&QUOT保存附加状态数据;注册"在ASP.Net身份(MVC)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用户注册,如期间存储更多的信息:姓,名和等

我的问题有两个部分:


  1. 如何注册过程中保存我的更多信息?

  2. 我目前的方法将引发错误:

验证失败的一个或多个实体。见'EntityValidationErrors了解详情属性。
我已经检查观察里VS,也可用于的try-catch,但它并没有帮助。

在此先感谢您的帮助!


IdentityModels.cs

 公共类ApplicationIdentityAccount:IdentityUser
{
  公共虚拟的ICollection< AccountProfile> AccountProfiles {搞定;组; }
}
公共类AccountProfile
{
      [键]
      公共字符串AccountProfileID {搞定;组; }
      [显示名称(名)]
      [StringLength(50)]
      [必需(的ErrorMessage =第一名称是必需)]
      公共字符串名字{获得;组; }
      [显示名称(中间名)]
      [StringLength(50)]
      公共字符串中间名{获得;组; }
      [显示名称(姓氏)]
      [StringLength(50)]
      [必需(的ErrorMessage =姓氏为必填)]
      公共字符串名字{获得;组; }      公共字符串userid {搞定;组; }
      [ForeignKey的(用户ID)]
      公共虚拟ApplicationIdentityAccount用户{搞定;组; }}
公共类ApplicationIdentityDbContext:IdentityDbContext< ApplicationIdentityAccount>
  {
 公共ApplicationIdentityDbContext()
 :基地(ApplicationIdentity,throwIfV1Schema:FALSE)
  {
  }
    公共静态ApplicationIdentityDbContext的Create()
      {
      返回新ApplicationIdentityDbContext();
      }公共System.Data.Entity.DbSet< AccountProfile> AccountProfile {搞定;组; } }

AccountViewModels.cs> RegisterViewModel

 公共类RegisterViewModel
    {    [需要]
    [显示(名称=用户名)]
    公共字符串用户名{获得;组; }    [需要]
    [显示(名称=名)]
    公共字符串名字{获得;组; }    [需要]
    [显示(名称=姓氏)]
    公共字符串名字{获得;组; }    [需要]
    [电子邮件地址]
    [显示(名字=电子邮件)]
    公共字符串电子邮件{获得;组; }    [需要]
    [StringLength(100,的ErrorMessage ={0}必须至少{2}字符长。,MinimumLength = 6)]
    [数据类型(DataType.Password)
    [显示(NAME =密码)]
    公共字符串密码{搞定;组; }    [数据类型(DataType.Password)
    [显示(NAME =确认密码)]
    [比较(密码的ErrorMessage =密码和确认密码不匹配。)
    公共字符串ConfirmPassword {搞定;组; }
}

AccountController.cs

  [HttpPost]
[使用AllowAnonymous]
[ValidateAntiForgeryToken]
公共异步任务<&的ActionResult GT;寄存器(RegisterViewModel模型)
      {
         如果(ModelState.IsValid)
              {
               VAR用户=新ApplicationIdentityAccount
                {
                   用户名= model.UserName,
                   电子邮件= model.Email,
                   AccountProfile =新[] {新AccountProfile()
                {
                    名字= model.FirstName,
                    姓氏= model.LastName
                }}
                };             VAR的结果=等待UserManager.CreateAsync(用户,model.Password);
             如果(result.Succeeded)
                {               等待SignInManager.SignInAsync(用户,isPersistent:假的,rememberBrowser:假);                        //有关如何启用帐户确认和重置密码,请访问http://go.microsoft.com/fwlink/?LinkID=320771更多信息
                        //发送一封电子邮件,该链接
                        //字符串code =等待UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        // VAR callbackUrl = Url.Action(ConfirmEmail,帐户,新的{用户id = user.Id,code = code},协议:Request.Url.Scheme);
                        //等待UserManager.SendEmailAsync(user.Id,确认您的账户,通过点击&LT请确认您的账户; A HREF = \\+ callbackUrl +\\>此处< / A>中);                        返回RedirectToAction(指数,家);
                    }
                    AddErrors(结果);
                    }
                //如果我们走到这一步,事情失败了,重新显示形式
                返回查看(模型);
    }

我知道我应该把里面的:

  VAR用户=新ApplicationIdentityAccount
                    {
                       用户名= model.UserName,
                       电子邮件= model.Email,
                    };


解决方案

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


  1. 您存储更多的信息方法是正确

  2. 您不能继续,除非你看到实际的错误,为了看你需要在其中创建用户添加这个细节。

     公共覆盖INT的SaveChanges()
    {
        尝试
        {
            返回base.SaveChanges();
        }
        赶上(DbEntityValidationException前)
        {
            //检索错误消息作为字符串列表。
            VAR errorMessages = ex.EntityValidationErrors
                    .SelectMany(X => x.ValidationErrors)
                    。选择(X => x.ErrorMessage);        //加入列表,一个字符串。
            变种fullErrorMessage =的string.join(;,errorMessages);        //用新合并原来的异常消息。
            VAR exceptionMessage = string.Concat(ex.Message,验证错误是:fullErrorMessage);        //抛出一个新的DbEntityValidationException与改进的异常信息。
            抛出新DbEntityValidationException(exceptionMessage,ex.EntityValidationErrors);
        }
    }


I need to store additional information during user registration such as: First Name, Last Name and etc.

My question has two parts:

  1. How can I save my additional information during Register?
  2. My current method throws error:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. I have already checked "Watch" inside VS and also used try-catch but it didn't help.

Thanks in advance for your help!


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

I know that I should place FirstName and LastName inside:

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

解决方案

Since your question has two parts:

  1. Your method for storing additional information is correct
  2. You can't proceed unless you see the actual error, in order to see the details you need to add this where you create the user.

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

这篇关于在&QUOT保存附加状态数据;注册&QUOT;在ASP.Net身份(MVC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆