应用程序:
- .NET 5 Web API
- 每个客户一个sql数据库
- JWT
问题:
有一个名为"APIController"的控制器,具有"Authenticate"方法。此方法正在从正文接收"UserName"one_answers"Password"。
有了这些参数,我可以检测客户的数据库,但我不知道如何将数据库(dbContext(设置到通过依赖注入获得的userManager中。
public class APIController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
public APIController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager
}
public async Task<IActionResult> Authenticate([FromBody] UserLoginModel model)
{
// Detect Customer's Database
DbContext dbContext = GetCustomersDbContext(model.UserName);
/*
Problem:
Check if the password is correct in the database I just found.
How can I set the dbContext in _userManager?
What I was trying to do:
var store = new UserStore<ApplicationUser>(dbContext);
var userManager = new UserManager<ApplicationUser>(store,
_userManager.Options,
_userManager.PasswordHasher,
_userManager.UserValidators,
_userManager.PasswordValidators,
_userManager.KeyNormalizer,
_userManager.ErrorDescriber,
_serviceProvider,
_logger);
*/
}
}
启动.cs
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.User.RequireUniqueEmail = false;
})
.AddEntityFrameworkStores<FileWebDbContext>()
.AddDefaultTokenProviders();
花了很多时间试图找到解决方案,如果有人给我任何想法,我将不胜感激!
更新下方的解决方案
解决方案:
public class APIController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly IOptions<IdentityOptions> _identityOptions;
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<UserManager<ApplicationUser>> _logger;
public APIController(
UserManager<ApplicationUser> userManager,
IOptions<IdentityOptions> identityOptions,
IServiceProvider serviceProvider,
ILogger<UserManager<ApplicationUser>> logger)
{
_userManager = userManager
_identityOptions = identityOptions;
_serviceProvider = serviceProvider;
_logger = logger;
}
public async Task<IActionResult> Authenticate([FromBody] UserLoginModel model)
{
// Detect Customer's Database
DbContext dbContext = GetCustomersDbContext(model.UserName);
// Solution
UserStore<ApplicationUser> store = new(dbContext);
UserManager<ApplicationUser> uManager = new(store,
_identityOptions,
_userManager.PasswordHasher,
_userManager.UserValidators,
_userManager.PasswordValidators,
_userManager.KeyNormalizer,
_userManager.ErrorDescriber,
_serviceProvider,
_logger);
}
}