title: ASP.NET Core session expires too soon
body: <p>I have an ASP.NET Core web app that uses session to store some variables. Everything works fine locally in any scenario, but for some reason i am unable to retrieve values from the session at some point (they are null) on an Azure machine.</p>
  
  <p><strong><em>Scenario:</em></strong></p>
  
  <ol>
  <li>Performing login, which redirects to another controller (storing user data in a session)</li>
  <li>Input some needed data and then redirecting to another controller (also storing some stuff in the session, and retrieving other values)</li>
  <li>In the Index page, setting some more data to the session. This controller's view is calling a javascript function that calls "<strong>OnScrollEnd</strong>" which is a method implemented by this controller.</li>
  <li>When the user scrolls down, the same javascript function is called (which calls <strong>OnScrollEnd</strong>)</li>
  <li>This method tries to retrieve data from the session, but now its null.</li>
  </ol>
  
  <p>(the above scenario demonstrates that essentially session state is working, but at some point it fails to retrieve values)</p>
  
  <p><strong><em>Log:</em></strong></p>
  
  <blockquote>
    <p>2019-04-23 14:12:34,220 [29] INFO 
    Microsoft.AspNetCore.Authorization.DefaultAuthorizationService
    [(null)] &lt;(null)> - Authorization was successful. 2019-04-23
    14:12:34,220 [29] INFO 
    Microsoft.AspNetCore.Authorization.DefaultAuthorizationService
    [(null)] &lt;(null)> - Authorization was successful. 2019-04-23
    14:12:34,220 [29] INFO 
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker [(null)]
    &lt;(null)> - Executing action method
    MyWebService.Controllers.AllCardsController.OnScrollEnd (MyWebService)
    - Validation state: Valid 2019-04-23 14:12:34,220 [29] INFO  Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker [(null)]
    &lt;(null)> - Executing action method
    MyWebService.Controllers.AllCardsController.OnScrollEnd (MyWebService)
    - Validation state: Valid 2019-04-23 14:12:34,220 [29] INFO  Microsoft.AspNetCore.Session.DistributedSession [(null)] &lt;(null)> -
    Accessing expired session, Key:c691acb5-f9ed-5a71-6ebb-f3a0980c4efd
    2019-04-23 14:12:34,220 [29] INFO 
    Microsoft.AspNetCore.Session.DistributedSession [(null)] &lt;(null)> -
    Accessing expired session, Key:c691acb5-f9ed-5a71-6ebb-f3a0980c4efd
    2019-04-23 14:12:34,221 [29] INFO 
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker [(null)]
    &lt;(null)> - Executed action
    MyWebService.Controllers.AllCardsController.OnScrollEnd (MyWebService)
    in 0.7545ms 2019-04-23 14:12:34,221 [29] INFO 
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker [(null)]
    &lt;(null)> - Executed action
    MyWebService.Controllers.AllCardsController.OnScrollEnd (MyWebService)
    in 0.7545ms 2019-04-23 14:12:34,223 [29] ERROR
    Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware [(null)]
    &lt;(null)> - An unhandled exception has occurred while executing the
    request.</p>
  </blockquote>
  
  <p>(Exception arises because the value fetched from the session was null)</p>
  
  <p><strong><em>Startup configuration:</em></strong></p>
  
  <pre><code>        public void ConfigureServices(IServiceCollection services)
          {
              var expiredSessionHours = Configuration.GetValue&lt;int&gt;("SessionExpireHours");
              var expiredSessionMinutes = Configuration.GetValue&lt;int&gt;("SessionExpireMinutes");
  
              services.AddLocalization(options =&gt; options.ResourcesPath = "Resources");
  
              services.AddAuthentication(options =&gt;
              {
                  options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                  options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                  options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
              })
              .AddCookie(options =&gt;
              {
                  options.LoginPath = "/Login";
                  options.ExpireTimeSpan = new TimeSpan(expiredSessionHours, expiredSessionMinutes, 0);
                  options.SlidingExpiration = true;
                  options.Cookie.Expiration = new TimeSpan(expiredSessionHours, expiredSessionMinutes, 0);
              });
  
              services.AddScoped&lt;IUserAuthentication, AuthenticationService&gt;();
              services.AddTransient&lt;IEncryptionService, EncryptionService&gt;();
              services.AddDbContext&lt;DatabaseContext&gt;(options =&gt;
                  options.UseSqlServer(Configuration.GetConnectionString("myConnectionString"))
                      .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking), 
                  ServiceLifetime.Transient);
  
              services.Configure&lt;CookiePolicyOptions&gt;(options =&gt;
              {
                  options.CheckConsentNeeded = context =&gt; false;
                  options.MinimumSameSitePolicy = SameSiteMode.None;
              });
  
              services.AddDistributedMemoryCache();
              services.AddSession(options =&gt;
              {
                  options.Cookie.HttpOnly = true;
                  options.Cookie.IsEssential = true;
                  options.IdleTimeout = new TimeSpan(expiredSessionHours, expiredSessionMinutes, 0);
              });
  
              services.AddMvc(options =&gt;
                  {
                      var policy = new AuthorizationPolicyBuilder()
                          .RequireAuthenticatedUser()
                          .Build();
                      options.Filters.Add(new AuthorizeFilter(policy));
                  })
                  .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
          }
  
          // Use this method to configure the HTTP request pipeline.
          public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
          {
              if (HostingEnvironment.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
              }
              else
              {
                  app.UseExceptionHandler("/Error");
                  app.UseHsts();
              }
  
              var supportedCultures = new[]
              {
                  new CultureInfo("en-US"),
              };
  
              app.UseRequestLocalization(new RequestLocalizationOptions
              {
                  DefaultRequestCulture = new RequestCulture("en-US"),
                  SupportedCultures = supportedCultures,
                  SupportedUICultures = supportedCultures
              });
  
              loggerFactory.AddLog4Net();
              app.UseStaticFiles();
              app.UseCookiePolicy();
              app.UseSession();
              app.UseAuthentication();
              app.UseMvc();
          }
  </code></pre>