本地IdentityServer4通过OpenIdConnect第一次访问站点时需要注册一个新用户。找到了在OnUserInformationReceived事件中执行此操作的“最佳位置” ,但不确定如何在事件处理程序(启动类)中访问 EF DbContext。没有用于获取 DbContext 的预配置实例(在其构造函数中请求其他依赖项)的 DI。public void ConfigureServices(IServiceCollection services){ // ... services.AddAuthentication(options => { options.DefaultScheme = "Cookies"; options.DefaultChallengeScheme = "oidc"; }) .AddCookie("Cookies") .AddOpenIdConnect("oidc", options => { options.SignInScheme = "Cookies"; // ... options.Events.OnUserInformationReceived = OnUserInformationReceived; }); // ...}private Task OnUserInformationReceived(UserInformationReceivedContext c){ var userId = c.User.Value<string>(JwtRegisteredClaimNames.Sub); // Call DbContext to insert User entry if doesn't exist. // Or there is another place to do that? return Task.CompletedTask;}
1 回答
动漫人物
TA贡献1815条经验 获得超10个赞
本UserInformationReceivedContext类包括一个HttpContext属性,它本身包括一个RequestServices属性。此RequestServices属性的类型为IServiceProvider,可用于访问在依赖注入容器中注册的服务。
这是一个使用示例GetService<T>:
private Task OnUserInformationReceived(UserInformationReceivedContext c)
{
var userId = c.User.Value<string>("sub");
var dbContext = c.HttpContext.RequestServices.GetService<YourDbContext>();
// Use dbContext here.
return Task.CompletedTask;
}
- 1 回答
- 0 关注
- 208 浏览
添加回答
举报
0/150
提交
取消