我正在尝试学习新的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&lt; -ApplicationUser,CustomRole,string,CustomUserLogin,CustomUserRole, CustomUserClaim-&gt; 不能分配给参数类型 IUserStore&lt; -ApplicationUser-&gt;
我在这里缺少什么?
答案 0 :(得分:7)
试试这个:
UserManager = new UserManager<ApplicationUser,string>(new UserStore<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim>(new myDbContext()));
注意我对UserManager
使用了不同的结构,我添加了string
作为您在ApplicationUser主键的代码中使用的第二种类型
由于您按照自己的方式实现了自定义用户/角色等,因此您需要在代码中使用UserManager
作为UserManager<ApplicationUser,string>
,以便将用户PK的类型作为字符串传递。< / p>
答案 1 :(得分:1)
这对我有用。如果您创建自定义用户和角色,似乎您必须创建自己的usermanager和userstore。这是派生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()));