Search code examples
asp.netasp.net-mvcasp.net-mvc-5dbcontextasp.net-identity-2

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


To learn Asp.Net Identity I have been using the Microsoft supplied Identity Samples template which can be downloaded via NuGet.

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

OR in the package manager console run:

Install-Package Microsoft.AspNet.Identity.Samples -Pre


PLEASE NOTE


This example is different than the one shipped with Visual Studios. The one shipped with VS still uses Identity V1.0 and the package on NuGet uses V2.1. As such I haven't verified this behavior in the VS example ONLY the NuGet one.

My simple question is this, Why is the DbContext instance (ApplicationDbContext) called on every single page I load and not just pages / operations which use the DB?

For example, if I put a breakpoint on the ApplicationDbContext method and then navigate from the Index page to the Contact page, or the Contact page to the Index page, or even to a random test page I created the DBContext method is fired and runs through all of the UserManager, RoleManager, and SignInManager code.

Is this normal? It seems to be a lot of extra work for returning views unrelated to the DB...


Solution

  • Identity has a configuration option to check for cookie - if it is still valid. Not sure what is the default from the nuget you downloaded, but you can change it in App_Start\Startup.Auth.cs, look for code looking like this:

            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))
                }
            });        
    

    You need to check your validateInterval parameter and if it is very small period of time, make it like 10-15 minutes.

    See here for full sample file.