我正在努力学习新的asp.net身份2.0是如何工作的,但由于文档很少,我遇到了不少障碍。
我在下面的代码是基于我读过的几个教程:
public class CustomRole : IdentityRole<string, CustomUserRole>
{
public CustomRole() { }
public CustomRole(string name) { Name = name; }
}
public class CustomUserRole : IdentityUserRole<string> { }
public class CustomUserClaim : IdentityUserClaim<string> { }
public class CustomUserLogin : IdentityUserLogin<string> { }
// define the application user
public class ApplicationUser : IdentityUser<string, CustomUserLogin, CustomUserRole,
CustomUserClaim>
{
[Required]
public bool IsActive { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> 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<ApplicationUser, CustomRole, string,
CustomUserLogin, CustomUserRole, CustomUserClaim>
{
static myDbContext()
{
Database.SetInitializer<myDbContext>(null);
}
public myDbContext()
: base("Name=myDbContext")
{
}
public DbSet<TestTable> TestTables { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new TestTableMap());
}
}
然后我有了这个代码:
// create the user manager
UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole,
CustomUserClaim>(
new myDbContext()));
我在该语句中得到一个错误,该错误表示参数类型为UserStore<-ApplicationUser,CustomRole,字符串,CustomUserLogin,CustomUserRole,CustomUserClaim->不可分配给参数类型IUserStore<-应用程序用户->
我在这里错过了什么?
试试这个:
UserManager = new UserManager<ApplicationUser,string>(new UserStore<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim>(new myDbContext()));
注意,我对UserManager
使用了不同的构造,我添加了string
作为ApplicationUser主键代码中使用的第二种类型
由于您以这种方式实现了自定义用户/角色等,因此需要在整个代码中使用UserManager
作为UserManager<ApplicationUser,string>
,以字符串形式传入用户PK的类型。
这对我很有效。如果你创建自定义用户和角色,似乎你必须创建自己的用户管理器和用户存储。这是派生的UM(您也可以以与角色管理器相同的方式创建):
public class ApplicationUserManager : UserManager<ApplicationUser, string>
{
public ApplicationUserManager(IUserStore<ApplicationUser, string> store)
: base(store)
{
}
}
public class ApplicationUserStore : UserStore<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
public ApplicationUserStore(ApplicationDbContext context)
: base(context)
{
}
}
然后创建UserManager:
ApplicationUserManager um = new ApplicationUserManager(new ApplicationUserStore(new ApplicationDbContext()));