如何从asp.net core 2数据库动态设置IdentityOptions?
我可以静态设置
services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
// Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 2;
options.Lockout.AllowedForNewUsers = true;
// User settings.
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = true;
});
但是我想从数据库中配置它。我对此有一些专栏。
var staticSetting = _unitOfWork.StaticSettings.GetAll().FirstOrDefault();
staticSetting.RequireDigit
staticSetting.RequireLowercase
staticSetting.RequireNonAlphanumeric
staticSetting.RequireUppercase
staticSetting.RequiredLength
staticSetting.RequiredUniqueChars
staticSetting.DefaultLockoutTimeSpanFromMinutes
staticSetting.MaxFailedAccessAttempts
staticSetting.AllowedForNewUsers
如何从哪里设置数据库?
答案 0 :(得分:0)
对于此要求,您可以从服务集合(如
)解析IUnitOfWork
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<IdentityOptions> identityOptions)
{
this.staticSetting = app.ApplicationServices.CreateScope().ServiceProvider
.GetRequiredService<ApplicationDbContext>().StaticSettings.FirstOrDefault();
identityOptions.Value.Password.RequireDigit = staticSetting.RequireDigit;
}
}
您无法通过IdentityOptions
配置services.Configure<IdentityOptions>
,因为此操作将在add-migration
期间和Configure
方法之前运行。
答案 1 :(得分:0)
如何通过以下代码实现IUnitOfWork:我可以得到它吗?
public class CustomIdentityOptions : IOptions<IdentityOptions>
{
**public IUnitOfWork _unitOfWork;**
public IdentityOptions Value { get; private set; }
public CustomIdentityOptions(IUnitOfWork unitOfWork)
{
var staticSetting = _unitOfWork.StaticSettings.GetAll().FirstOrDefault();
Value = new IdentityOptions
{
Lockout = new LockoutOptions
{
AllowedForNewUsers = true,
DefaultLockoutTimeSpan = TimeSpan.FromMinutes(1),
MaxFailedAccessAttempts = staticSetting.MaxFailedAccessAttempts
}
};
}
}