我如何创建UserManager的实例

use*_*480 4 c# asp.net-mvc asp.net-identity

我试图了解新的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());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我有这个代码:

// create the user manager
        UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole,
    CustomUserClaim>(
            new myDbContext()));
Run Code Online (Sandbox Code Playgroud)

我在这个语句中得到一个错误,说参数类型UserStore <-ApplicationUser,CustomRole,string,CustomUserLogin,CustomUserRole,CustomUserClaim->不能分配给参数类型IUserStore <-ApplicationUser->

我在这里错过了什么?

dim*_*ima 9

试试这个:

UserManager = new UserManager<ApplicationUser,string>(new UserStore<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim>(new myDbContext()));
Run Code Online (Sandbox Code Playgroud)

注意我使用了不同的结构UserManager,我添加string了你在ApplicationUser主键的代码中使用的第二种类型

既然你实现自定义用户/角色/等你的方式,你需要使用UserManagerUserManager<ApplicationUser,string>整个代码在用户PK作为一个字符串类型传递.