我如何创建UserManager的实例

我正在尝试学习新的asp.net身份2.0如何工作,但是几乎没有文档,我遇到了很多绊脚石。

我在下面的代码基于我读过的几个教程:

public class CustomRole : IdentityRole { public CustomRole() { } public CustomRole(string name) { Name = name; } } public class CustomUserRole : IdentityUserRole { } public class CustomUserClaim : IdentityUserClaim { } public class CustomUserLogin : IdentityUserLogin { } // define the application user public class ApplicationUser : IdentityUser { [Required] public bool IsActive { get; set; } 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 partial class myDbContext : IdentityDbContext { static myDbContext() { Database.SetInitializer(null); } public myDbContext() : base("Name=myDbContext") { } public DbSet TestTables { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new TestTableMap()); } } 

然后我有这个代码:

 // create the user manager UserManager = new UserManager(new UserStore( new myDbContext())); 

我在这个语句中得到一个错误,说参数类型UserStore 不能分配给参数类型IUserStore

我在这里想念的是什么?

试试这个:

 UserManager = new UserManager(new UserStore(new myDbContext())); 

注意我对UserManager使用不同的构造,我添加了string作为您在ApplicationUser主键的代码中使用的第二种类型

由于您按照自己的方式实现了自定义用户/角色/等,因此您需要在整个代码中使用UserManager作为UserManager将User PK的类型作为字符串传递。

这对我有用。 如果您创建自定义用户和角色,似乎您必须创建自己的usermanager和userstore。 这是派生的UM(您也可以像使用角色管理器一样创建):

 public class ApplicationUserManager : UserManager { public ApplicationUserManager(IUserStore store) : base(store) { } } public class ApplicationUserStore : UserStore { public ApplicationUserStore(ApplicationDbContext context) : base(context) { } } 

然后创建UserManager:

 ApplicationUserManager um = new ApplicationUserManager(new ApplicationUserStore(new ApplicationDbContext()));