title: How to set session idle timeout in C#, .NET 5.0?
body: <p><strong>Final Update:</strong> It turned out that the issue was caused by authentication timeouts rather than session timeouts. These are different things and need to be set separately. Here is the fix I ended up with:</p>
  <p>Create a timeout value in appsettings.json. This value will be used to configure session and authorization timeouts. (You can name this whatever you want.)</p>
  <p><code>&quot;IdleTimeoutMinutes&quot;: 60,</code></p>
  <p>Set session timeout in Startup.cs.</p>
  <pre><code>services.AddSession(options =&gt;
  {
      options.IdleTimeout = TimeSpan.FromMinutes(Configuration.GetValue&lt;double&gt;(&quot;IdleTimeoutMinutes&quot;));
      options.Cookie.HttpOnly = true;
      options.Cookie.IsEssential = true;
  });       
  </code></pre>
  <p>Configure authentication timeout in Startup.cs.</p>
  <pre><code>services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
      .AddNegotiate()
      .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
  options =&gt;
  {
      options.LoginPath = new PathString(&quot;/Account/Login/LogOn/&quot;);
      options.AccessDeniedPath = new PathString(&quot;/Account/Login/AccessDenied/&quot;);
      options.SlidingExpiration = true;
      options.ExpireTimeSpan = TimeSpan.FromMinutes(Configuration.GetValue&lt;double&gt;(&quot;IdleTimeoutMinutes&quot;));
  });
  </code></pre>
  <p>Configure authentication cookie timeout in LoginController.cs.</p>
  <pre><code>await HttpContext.SignInAsync(
      CookieAuthenticationDefaults.AuthenticationScheme, claims.Get(currentUser),
          new AuthenticationProperties
          {
              ExpiresUtc = DateTime.UtcNow.AddMinutes(Configuration.GetValue&lt;double&gt;(&quot;IdleTimeoutMinutes&quot;)),
              IsPersistent = true,
              AllowRefresh = true
          });
  </code></pre>
  <p>I found this information here: <a href="https://www.blakepell.com/blog/asp-net-core-cookie-authentication-timing-out" rel="nofollow noreferrer">https://www.blakepell.com/blog/asp-net-core-cookie-authentication-timing-out</a></p>
  <p>(Archived page: <a href="https://web.archive.org/web/20220411151611/https://www.blakepell.com/blog/asp-net-core-cookie-authentication-timing-out" rel="nofollow noreferrer">https://web.archive.org/web/20220411151611/https://www.blakepell.com/blog/asp-net-core-cookie-authentication-timing-out</a>)</p>
  <p>Note that the <code>Cookie.Expiration</code> setting described at this link no longer works. It returns a error &quot;Cookie.Expiration is ignored, use ExpireTimeSpan instead&quot;. I left out that line and everything else worked.</p>
  <p><strong>Update:</strong> As a test, I changed the session IdleTimeout value from 30 minutes to 10 seconds and discovered that the session timeout is, in fact, working as expected. There is a different, unknown, timeout that is breaking things after 15 minutes, regardless of the session IdleTimeout value. Where is this 15 minute timeout coming from?</p>
  <p>Things that break after IdleTimeout seconds:</p>
  <ol>
  <li><code>HttpContext.Session.GetString(SessionKeySheetData)</code> in .cs code returns a &quot;Value cannot be null&quot; error. This is expected. The session IdleTimeout is working correctly.</li>
  </ol>
  <p>Things that break after 15 minutes idle, regardless of the session IdleTimeout value:</p>
  <ol>
  <li>JavaScript Ajax calls result in an authentication popup asking for user name and password. This does not occur anywhere else in this application that uses Windows authentication and it does not accept my usual Windows login user name and password. I can work around this by adding a <code>[AllowAnonymous]</code> directive to the relevant code.</li>
  <li><code>Context.Request.Form(&quot;&lt;form field id&gt;&quot;)</code> in .cshtml code returns a &quot;Incorrect Content-type&quot; error.</li>
  </ol>
  <p>Apparently there are two idle timeouts here. The session timeout, controlled by the IdleTimeout value, is working as expected. But there is another timeout of 15 minutes that is not related to the session timeout. Where is this other timeout coming from and how can it be changed?</p>
  <p><strong>Original question:</strong></p>
  <p>I'm a beginning C# coder and I have been tasked with maintaining an existing web application written in C# with .NET 5.0. The current session timeout seems to be 15 minutes and I would like to increase it. This question has been asked and answered many times, but before flagging this as a duplicate, understand that most of those questions and answers are for older versions of .NET and are not applicable to the current version. Also, nearly everyone has a different answer, and I have not been able to get any of them to work.</p>
  <p>The answers I have found fall into four categories:</p>
  <ol>
  <li><p>IIS configuration changes. For development I am using the IIS Express that comes with VS 2019. I have installed the latest IIS Manager app, but nothing I see there matches the answers I find online. I presume those answers are for older versions of IIS, and I do not see any session timeout configuration in the current version of IIS Manager. Example: <a href="https://beansoftware.com/ASP.NET-Tutorials/Session-Timeout-Expiration.aspx" rel="nofollow noreferrer">https://beansoftware.com/ASP.NET-Tutorials/Session-Timeout-Expiration.aspx</a></p>
  </li>
  <li><p>Project configuration changes. I have found many, many pages suggesting to set <code>sessionState timeout=&quot;&lt;minutes&gt;&quot;</code> in web.config. However my project does not have a web.config and it is my understanding that this is used only in older .NET versions. Example: <a href="https://stackoverflow.com/questions/648992/session-timeout-in-asp-net">Session timeout in ASP.NET</a></p>
  </li>
  <li><p>Create a JavaScript/Ajax function to keep the session alive by calling a dummy HTTP Handler. I haven't been able to get this to work and it seems like an ugly hack if there is a way to simply change the timeout configuration. Example: <a href="https://stackoverflow.com/questions/1431733/keeping-asp-net-session-open-alive">Keeping ASP.NET Session Open / Alive</a></p>
  </li>
  <li><p>Change the session timeout programmatically. I think this would be a good option if I could get it to work, but adding <code>public TimeSpan IdleTimeout = TimeSpan.Parse(&quot;01:00:00&quot;);</code> to the code does not seem to have any effect. Example: <a href="https://docs.microsoft.com/en-us/dotnet/api/system.web.configuration.processmodelsection.idletimeout?view=netframework-4.8" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/api/system.web.configuration.processmodelsection.idletimeout?view=netframework-4.8</a></p>
  </li>
  </ol>
  <p>Any help would be appreciated.</p>
  <p>Edit: Added Startup.cs below, as requested.</p>
  <pre><code>using ILawProductionApp.Domain.Context;
  using ILawProductionApp.Domain.Helpers.Sheets;
  using ILawProductionApp.Domain.Shared.Contracts;
  using ILawProductionApp.Domain.Shared.Repository;
  using ILawProductionApp.Infrastructure.Contexts;
  using ILawProductionApp.Infrastructure.Interfaces;
  using ILawProductionApp.Infrastructure.Interfaces.Repositories;
  using ILawProductionApp.UI.Areas.Account.Managers.Authorization;
  using ILawProductionApp.UI.Helpers;
  using Microsoft.AspNetCore.Authentication.Cookies;
  using Microsoft.AspNetCore.Authentication.Negotiate;
  using Microsoft.AspNetCore.Authorization;
  using Microsoft.AspNetCore.Builder;
  using Microsoft.AspNetCore.Hosting;
  using Microsoft.AspNetCore.Http;
  using Microsoft.AspNetCore.Mvc.Authorization;
  using Microsoft.EntityFrameworkCore;
  using Microsoft.Extensions.Configuration;
  using Microsoft.Extensions.DependencyInjection;
  using Microsoft.Extensions.Hosting;
  using System;
  
  namespace ILawProductionApp.UI
  {
      public class Startup
      {
          public Startup(IConfiguration configuration)
          {
              Configuration = configuration;
          }
  
          public IConfiguration Configuration { get; }
  
          // This method gets called by the runtime. Use this method to add services to the container.
          public void ConfigureServices(IServiceCollection services)
          {            
              services.AddHttpContextAccessor();
              services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
                  .AddNegotiate()
                  .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
              options =&gt;
              {
                  options.LoginPath = new PathString(&quot;/Account/Login/LogOn/&quot;);
                  options.AccessDeniedPath = new PathString(&quot;/Account/Login/AccessDenied/&quot;);
  
              });
  
              services.AddDbContext&lt;AppIdentityDbContext&gt;(options =&gt; options.
             UseOracle(Environment.GetEnvironmentVariable(Configuration[&quot;EnvironmentVars:DefaultConnectionString&quot;])));
  
              services.AddMvc(config =&gt;
              {
                  var policy = new AuthorizationPolicyBuilder()
                                   .RequireAuthenticatedUser()
                                   .Build();
                  config.Filters.Add(new AuthorizeFilter(policy));
              });
  
              services.AddSingleton&lt;IAuthorizationPolicyProvider, LawPermissionPolicyProvider&gt;();
              services.AddScoped&lt;IAuthorizationHandler, RolesAuthorizationHandler&gt;();
              services.AddScoped&lt;IAuthorizationHandler, LawPermissionAuthorizationHandler&gt;();
              //services.AddScoped&lt;IAuthorizationHandler, ProcessCalApp2AuthorizationHandler&gt;();
              //services.AddScoped&lt;IAuthorizationHandler, ProccessGlassAppAuthorizationHandler&gt;();
              services.AddDistributedMemoryCache();
              services.AddSession(options =&gt;
              {
                  options.IdleTimeout = TimeSpan.FromSeconds(Configuration.GetValue&lt;double&gt;(&quot;SessionTimeoutSeconds&quot;));
                  options.Cookie.HttpOnly = true;
                  options.Cookie.IsEssential = true;
              });       
              services.AddControllersWithViews().AddSessionStateTempDataProvider();
              services.AddDbContext&lt;ApplicationILawDbContext&gt;(options =&gt; options.UseLazyLoadingProxies()
              .UseOracle(Environment.GetEnvironmentVariable(Configuration[&quot;EnvironmentVars:DefaultConnectionString&quot;])));
              services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
              services.AddScoped&lt;IAdminUnitOfWork, AdminUnitOfWork&gt;();
              services.AddScoped&lt;IUnitOfWork, UnitOfWork&gt;();
              services.AddScoped&lt;ICa2RunUtil, Ca2RunUtil&gt;();
              services.AddScoped&lt;ILawGaRunUtil, LawGaRunUtil&gt;();
              services.AddTransient&lt;ISheetModifier, SheetModifier&gt;();
   
          }
  
          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
          public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
          {
              if (env.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
              }
              else
              {
                  app.UseExceptionHandler(&quot;/Home/Error&quot;);
                  // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                  app.UseHsts();
              }
              app.UseHttpsRedirection();
              app.UseStaticFiles();
              app.UseRouting();
              app.UseAuthentication();
              app.UseAuthorization();
              app.UseSession();
              app.UseEndpoints(endpoints =&gt;
              {
                  endpoints.MapControllerRoute(
                     name: &quot;Adminstration&quot;,
                     pattern: &quot;{area:exists}/{controller=Admin}/{action=Index}/{id?}&quot;);
                                 
                  endpoints.MapControllerRoute(
                        name: &quot;Account&quot;,
                        pattern: &quot;{area:exists}/{controller=Account}/{action=Index}/{id?}&quot;
                  );
  
                  endpoints.MapControllerRoute(
                      name: &quot;default&quot;,
                      pattern: &quot;{controller=Home}/{action=Index}/{id?}&quot;);
                  endpoints.MapRazorPages();
              });
          }
      }
  }
  </code></pre>