自定义ASP.NET标识

时间:2014-09-07 07:32:51

标签: c# asp.net asp.net-identity

我必须自定义ASP.NET Identity实体。

我有这些课程:

<!-- language: c# -->

public class ApplicationUser: IdentityUser<string, ApplicationLogin, ApplicationUserRole, ApplicationClaim> {}

public class: UserStore<ApplicationUser, ApplicationRole, string, ApplicationLogin, ApplicationUserRole, ApplicationClaim> {}

public class ApplicationUserManager: UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {}
}

在这种情况下如何为DI创建IUserStore<ApplicationUser>的实例?


由于使用了工作单元存储库,我无法从IdentityDbContext派生我的DbContex。 我找到了类似的问题here

1 个答案:

答案 0 :(得分:1)

您需要创建一些其他类和接口:

public interface IApplicationUserStore : IUserStore<ApplicationUser, string>
{

}

public class ApplicationUserStore :
    UserStore<ApplicationUser, ApplicationRole, Guid, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>,
    IApplicationUserStore
{
    public ApplicationUserStore()
        : base(new ApplicationDbContext())
    {

    }

    public ApplicationUserStore(ApplicationDbContext context)
        : base(context)
    {

    }
}

并创建类ApplicationDbContext

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public ApplicationDbContext()
        : base("AuthenticationConnectionString")
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
    ...
}

然后从您的ApplicationUserManager中调用

var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<ApplicationDbContext>()));

这是在构造函数中接收IApplicationUserStore的完整类ApplicationUserManager:

public class ApplicationUserManager : UserManager<ApplicationUser, Guid>
    {
        public ApplicationUserManager(IApplicationUserStore store)
            : base(store)
        {
        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<ApplicationDbContext>())) { PasswordHasher = new CustomPasswordHasher() };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = false,
            };

            return manager;
        }
    }