英文:
.NET How to access the DBContext within OIDC Middleware
问题
我有以下的 Startup.cs
中的 #ConfigureServices
方法:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => { Configuration.Bind("AzureAd", options); });
// 注册 TracingContext 以访问数据库
services.AddDbContext<TracingContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
options.Events = new OpenIdConnectEvents
{
OnTokenValidated = ctx =>
{
// 获取用户的电子邮件
var email = ctx.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
// 如何从上面访问 TracingContext?
// 在这里编写代码
// 添加声明
var claims = new List<Claim>
{
new Claim(ClaimTypes.Role, "HQUser")
};
var appIdentity = new ClaimsIdentity(claims);
ctx.Principal.AddIdentity(appIdentity);
return Task.CompletedTask;
},
};
});
}
由于我在方法中使用 services.AddDbContext(...)
定义了 TracingContext(DBContext)
,在 OICD 中间件中如何访问 TracingContext?
我需要在这一点上从数据库中检索用户的角色。
谢谢
英文:
I have the following Startup.cs
#ConfigureServices
method:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => { Configuration.Bind("AzureAd", options); });
//Register TracingContext to access the DB
services.AddDbContext<TracingContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
options.Events = new OpenIdConnectEvents
{
OnTokenValidated = ctx =>
{
// Get the user's email
var email = ctx.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
// Query the database to get the role
**// BUT: How do I access the TracingContext from above?**
**// CODE HERE **
// Add claims
var claims = new List<Claim>
{
new Claim(ClaimTypes.Role, "HQUser")
};
var appIdentity = new ClaimsIdentity(claims);
ctx.Principal.AddIdentity(appIdentity);
return Task.CompletedTask;
},
};
});
}
Since I have defined the TracingContext (DBContext)
in the method by using services.AddDbContext(...)
, how can I access the TracingContext in the OICD MiddleWare?
I need to retrieve the User's role from the database at this point.
Thank you
答案1
得分: 1
你可以使用 HttpContext.RequestServices.GetRequiredService
来获取依赖项:
var db = ctx.HttpContext.RequestServices.GetRequiredService<YourDbContext>();
英文:
You can use HttpContext.RequestServices.GetRequiredService
to get the dependency :
var db = ctx.HttpContext.RequestServices.GetRequiredService<YourDbContext>();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论