亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用戶首次使用 OpenId Connect 登錄后,將新 UserId 放入數據庫的位置在哪里?

用戶首次使用 OpenId Connect 登錄后,將新 UserId 放入數據庫的位置在哪里?

C#
慕田峪7331174 2021-10-24 17:54:58
本地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;

}


查看完整回答
反對 回復 2021-10-24
  • 1 回答
  • 0 關注
  • 237 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號