将用户名和姓氏添加到ASP.NET标识2?

我转而使用新的ASP.NET Identity 2.我实际上使用的是Microsoft ASP.NET Identity Samples 2.0.0-beta2。

任何人都可以告诉我在哪里以及如何修改代码,以便它存储用户的名字和姓氏以及用户详细信息。 这现在是否是索赔的一部分,如果是这样,我怎么能添加它?

我假设我需要在这里添加这个帐户控制器中的寄存器方法:

if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { var 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 this link: link"); ViewBag.Link = callbackUrl; return View("DisplayEmail"); } AddErrors(result); } 

此外,如果我添加了名字和姓氏,那么它存储在数据库中的哪个位置? 我是否需要在表格中为此信息创建其他列?

您需要将它添加到您的ApplicationUser类中,因此如果您使用Identity Samples,我想您在IdentityModels.cs有类似的东西

 public class ApplicationUser : IdentityUser { public async Task GenerateUserIdentityAsync(UserManager manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } } 

添加名字和姓氏后,它将如下所示:

 public class ApplicationUser : IdentityUser { public async Task GenerateUserIdentityAsync(UserManager manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } public string FirstName { get; set; } public string LastName { get; set; } } 

然后,当您注册用户时,您需要将它们添加到列表中,因为它们是在ApplicationUser类中定义的

 var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = "Jack", LastName = "Daniels" }; 

执行迁移后,名字和姓氏将在AspNetUsers表中结束

我意识到这篇文章已经有几年了,但是随着ASP.NET Core的发展,我最终遇到了类似的问题。 接受的答案建议您更新用户数据模型以捕获此数据。 我不认为这是一个糟糕的建议,但从我的研究声称是存储这些数据的正确方法。 请参阅ASP .NET Identity和User.Identity.Name全名mvc5中 的声明是什么 。 后者由Microsoft的ASP.NET身份团队的人员回答。

这是一个简单的代码示例,展示了如何使用ASP.NET Identity添加这些声明:

 var claimsToAdd = new List() { new Claim(ClaimTypes.GivenName, firstName), new Claim(ClaimTypes.Surname, lastName) }; var addClaimsResult = await _userManager.AddClaimsAsync(user, claimsToAdd);