如何在 OnSignedIn .net Core - 实体框架中访问数据库数据

Posted

技术标签:

【中文标题】如何在 OnSignedIn .net Core - 实体框架中访问数据库数据【英文标题】:How to access the database data in OnSignedIn .net Core - Entity framework 【发布时间】:2021-05-10 17:21:03 【问题描述】:

当用户登录到 .net 核心 MVC 程序时,我需要使用登录的用户 ID 从数据库中查看特定于用户的数据,并将这些数据保存到当前 cookie。以下是我现在走的路。如果出现问题,请告诉我如何执行此操作。

有没有类似的访问方式

dbcontext.footable.where(x=> x.id = "somevalue")

Startup.cs

services.ConfigureIdentitySettings(apiSetting);

ConfigureIdentitySettings.cs

public static class IdentitySettingsExtensions
    
        // Identity Setup
        public static void ConfigureIdentitySettings(this IServiceCollection services, IConfigurationSection apiSetting)
        
            services.ConfigureApplicationCookie(options =>
            
                options.Cookie.Name = "foo";
                options.ExpireTimeSpan = TimeSpan.FromMinutes(Configurations.ExipireTimeSpan);
                options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
                options.LoginPath = Configurations.LoginPath;
                options.LogoutPath = Configurations.LogoutPath;
                options.AccessDeniedPath = Configurations.AccessDeniedPath;
                options.SlidingExpiration = true;
                options.Events = new CookieAuthenticationEvents
                
                    OnSignedIn = context =>
                    
                        // Here i got current logged in user id
                        var loggedInUserRole = context.Principal.GetLoggedInUserId();

                        //I need to access database data from here after that adding those data into current cookie
                        return Task.CompletedTask;
                                        
                ;
            );

            services.Configure<IdentityOptions>(options =>
            
                // Providers
                //options.Tokens.PasswordResetTokenProvider = PasswordResetTokenProviderName;
                //options.Tokens.EmailConfirmationTokenProvider = ConfirmEmailTokenProviderName;
                options.SignIn.RequireConfirmedEmail = true;
                options.User.RequireUniqueEmail = true;              

                options.Password.RequireUppercase = Configurations.RequireUppercase;
                options.Password.RequireLowercase = Configurations.RequireLowercase;
                options.Password.RequireDigit = Configurations.RequireDigit;
                options.Password.RequiredLength = Configurations.RequireLength;
                options.Password.RequireNonAlphanumeric = Configurations.RequireNonAlphanumeric;
            );

            var firstLifeSpan = Convert.ToInt32(apiSetting["FirstEmailConfirmationLifeSpan"]);
            var secondLifeSpan = Convert.ToInt32(apiSetting["SecondEmailConfirmationLifeSpan"]);
            services.Configure<DataProtectionTokenProviderOptions>(o =>
                o.TokenLifespan = TimeSpan.FromDays(firstLifeSpan > secondLifeSpan ? firstLifeSpan : secondLifeSpan));

        
    

【问题讨论】:

【参考方案1】:

您可以通过OnSignedIn 方法访问数据库数据,如下所示:

services.ConfigureApplicationCookie(options =>

    //...
    options.Events = new CookieAuthenticationEvents
    
        OnSignedIn = context =>
        

            //Build an intermediate service provider
            var sp = services.BuildServiceProvider();

            //Resolve the services from the service provider
            var myDbContext = sp.GetService<ApplicationDbContext>();

            //access database data...
            var data = myDbContext.footable.Where(x => x.Id== "xxx");

            //...
            return Task.CompletedTask;
        
    ;
);

【讨论】:

以上是关于如何在 OnSignedIn .net Core - 实体框架中访问数据库数据的主要内容,如果未能解决你的问题,请参考以下文章

如何按照存储库模式在 Asp.Net Core 5.0 项目上实现 .Net Core Identity?

如何在ubuntu安装.net core sdk

ASP.NET Core中的缓存[1]:如何在一个ASP.NET Core应用中使用缓存

如何在 Visual Studio 中将 .NET Framework 更改为 .NET Standard/Core?

如何使用 EF Core 在 ASP.NET Core 中取消应用迁移

如何将 .NET Core 2.2 Web API 迁移到 .NET Core 3.0?