【问题标题】:Accessing UserManager with PasswordHasher outside of controller在控制器外使用 PasswordHasher 访问 UserManager
【发布时间】:2018-02-19 10:09:12
【问题描述】:

我有一个使用带有身份和实体框架核心的 asp.net core 2.0 的网络应用程序。创建数据库后,我试图创建几个用户。我创建了从 Program.Main() 调用的 DbInitializer 类

    public static void Main(string[] args)
    {
        var host = BuildWebHost(args);

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                var context = services.GetRequiredService<ApplicationDbContext>();
                DbInitializer.Initialize(context);
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred while seeding the database.");
            }
        }

        host.Run();
    }

问题是我无法在我的班级中使用正确的 PasswordHasher 访问 UserManager。我试试这个answer,然后像这样创建了新的 UserManager

 var store = new UserStore<ApplicationUser>(context);
 var hasher = new PasswordHasher<ApplicationUser>();
 var manager = new UserManager<ApplicationUser>(store, null, hasher, null, null, null, null, null, null);
 await manager.CreateAsync(user, "password");

然后我创建用户。用户已创建,我可以在数据库中看到他,问题是我无法使用给定的密码登录。我认为问题在于我创建了新的 PasswordHasher。如何访问应用程序中使用的 UserManager?..

【问题讨论】:

    标签: asp.net asp.net-identity .net-core-2.0


    【解决方案1】:

    我在尝试将用户植入我的数据库时遇到了类似的问题,这就是我的解决方法。

    尝试将服务而不是上下文传递给您的 Initialize 方法:

    DbInitializer.Initialize(services);
    

    然后更新你的 Initialize 方法:

    public static void Initialize(IServiceProvider services) {
    
        var context = services.GetRequiredService<ApplicationDbContext>();
        //Do stuff with context        
    
        //Obtain reference to UserManager
        var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
    
        // Set properties for new User
        ApplicationUser user = new ApplicationUser
        {
            UserName = "admin@myapp.local",
            Email = "admin@myapp.local"
        };
    
        //Set password
        string password = "Change.Me99";
    
        //Create new user
        var result = userManager.CreateAsync(user, password);
    
        //Check the result
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-31
      • 1970-01-01
      • 2015-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多