Asp.Net DbContext ... 为什么它在我的应用程序中被如此频繁地调用? ... 困惑

Asp.Net DbContext ... Why is it called so often in my app? ... Confusion

为了学习 Asp.Net Identity,我一直在使用 Microsoft 提供的 Identity Samples 模板,可以通过 NuGet 下载该模板。

https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples/2.1.0-alpha1

或在程序包管理器控制台中 运行:

安装包 Microsoft.AspNet.Identity.Samples -Pre


请注意


此示例与 Visual Studios 附带的示例不同。 VS 附带的仍然使用 Identity V1.0,而 NuGet 上的包使用 V2.1。因此,我没有在 VS 示例中仅验证 NuGet 示例中的这种行为。

我的简单问题是,为什么在我加载的每个页面上调用 DbContext 实例 (ApplicationDbContext) 而不仅仅是使用数据库的页面/操作?

例如,如果我在 ApplicationDbContext 方法上放置一个断点,然后从索引页面导航到联系页面,或者从联系页面导航到索引页面,甚至导航到我创建 DBContext 方法的随机测试页面通过所有 UserManager、RoleManager 和 SignInManager 代码被触发并 运行s。

这正常吗?返回与数据库无关的视图似乎需要做很多额外的工作...

Identity 有一个配置选项来检查 cookie - 如果它仍然有效。不确定您下载的 nuget 的默认值是什么,但您可以在 App_Start\Startup.Auth.cs 中更改它,查找如下所示的代码:

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });        

您需要检查您的 validateInterval 参数,如果时间非常短,请设置为 10-15 分钟。

有关完整示例文件,请参阅 here