asp.net-mvc - 在 AspNetCore Mvc 中使用依赖注入配置 CookieAuthenticationOptions
问题描述
有没有办法使用依赖注入来配置 cookie 身份验证选项?我想从数据库中获取一些设置,但此时我无权访问 DatabaseContext。
public void ConfigureServices(IServiceCollection services)
{
...
services
.AddAuthentication(Authentication.scheme)
.AddCookie(Authentication.scheme, options =>
{
options.ExpireTimeSpan = new TimeSpan(30, 0, 0, 0, 0);
options.Cookie.IsEssential = true;
options.Cookie.Name = ".AUTH-Cookie";
options.ReturnUrlParameter = "returnUrl";
options.LoginPath = "/Security/SignIn";
options.LogoutPath = "/Security/SignOut";
options.EventsType = typeof(CookieAuthenticationEvents);
});
...
}
我可以使用 AddOptions() 和 Configure() 对 ConfigureServices 中的其他项目执行此操作,但我无法弄清楚如何使用 CookieAuthenticationOptions...
services
.AddOptions<MvcOptions>()
.Configure<IDisplayMetadataProvider>((options, localizationMetadataProvider) =>
{
options.ModelMetadataDetailsProviders.Add(localizationMetadataProvider);
});
我试图用 CookieAuthenticationOptions 做同样的事情,但它似乎并没有以同样的方式工作......
解决方案
关于如何在 cookie 身份验证选项中从数据库中获取数据,这里有一个简单的示例:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("YourConnnectionString")));
var sp = services.BuildServiceProvider();
var myDbContext = sp.GetService<MyDbContext>();
var data = GetData(myDbContext);
services.AddAuthentication(Authentication.scheme)
.AddCookie(Authentication.scheme,options =>
{
options.LoginPath = data;
//...
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//be sure you have added authentication middleware
app.UseAuthentication();
//if you use asp.net core 3.x,also need to add this
//app.UseAuthorization();
}
public static string GetData(MyDbContext _context)
{
//get the data from database
var data = _context.Tables.Select(j => j.Loginpath).FirstOrDefault();
return data;
}
推荐阅读
- cmake - 在 Windows 上为 cmake 配置 Poco
- ghostscript - Ghostscript 显示设备 rectangle_request 是否有效?
- javascript - CSS - 第 n 个子项/类型或 javascript
- node.js - 如何使消息仅在特定类别中发送
- python - 如何在 Django 中使用 SearchVector SearchRank 和 icontain?
- c# - 是否可以在 LINQ 查询中将类型作为字符串传递?
- javascript - 为什么 JavaScript 扩展符号在这里不起作用
- python - 在python中计算两个列表中的相等元素
- c++ - 使用 cublasSgetriBatched 在 gpu 上求逆两个矩阵
- c++ - 如何为 std::unordered_map 编写自定义 hash_function
在cpp?