我如何创建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()));
- 如何在ASP.Net MVC 5视图中获取ApplicationUser的自定义属性值?
- Asp.net Identity使用密码和Azure Active Directory身份validation
- MVC 5:我应该从IdentityUser类inheritance我的用户吗?
- 在控制器中生成令牌
- ASP.NET身份检查用户角色无效
- 使ASP.NET Identity 2.0电子邮件确认令牌适用于WCF和MVC
- 如何注入UserManager和SignInManager
- JavaScript:如何生成像C#这样的Rfc2898DeriveBytes?
- 具有特殊字符的ASP.NET MVC标识电子邮件/用户名