【发布时间】:2015-02-11 15:17:26
【问题描述】:
我创建了一个新项目,并将我的代码转换为使用整数 ID,而不是遵循本指南的 GUID:
现在我想为我的用户添加一些自定义字段,比如 FirstName。
我的 RegisterViewModel:
public class RegisterViewModel
{
[Required]
[Display(Name = "First Name")]
public string FirstName { 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; }
}
这行得通,我的名字被保存到数据库中。我的问题是我无法检索它,我不确定我做错了什么。
这是我的 IdentityModels.cs
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
public string FirstName { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> 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
userIdentity.AddClaim(new Claim("FirstName", this.FirstName));
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
public class CustomUserRole : IdentityUserRole<int> { }
public class CustomUserClaim : IdentityUserClaim<int> { }
public class CustomUserLogin : IdentityUserLogin<int> { }
public class CustomRole : IdentityRole<int, CustomUserRole>
{
public CustomRole() { }
public CustomRole(string name) { Name = name; }
}
public class CustomUserStore : UserStore<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
public CustomUserStore(ApplicationDbContext context)
: base(context)
{
}
}
public class CustomRoleStore : RoleStore<CustomRole, int, CustomUserRole>
{
public CustomRoleStore(ApplicationDbContext context)
: base(context)
{
}
}
user.FirstName 始终为空。
谢谢
【问题讨论】:
-
显示您尝试访问
user.FirstName的方式? -
在 GenerateUserIdentityAsync 方法中: var user = await manager.FindByEmailAsync(userIdentity.Name); userIdentity.AddClaim(new Claim("FirstName", user.FirstName));
-
您确定
user.FirstName为空,而user不为空吗?如果您从数据库加载整个用户并且 FirstName 存储在该数据库中,则应该没有问题。显示从数据库加载用户的示例代码。 -
呃,你是对的。在测试时,我创建了两个用户,一个有 FirstName 值,另一个没有。我在用错误的用户进行测试!我显然不是很聪明。谢谢
标签: c# asp.net-mvc-5 asp.net-identity