Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to increase session timeout in ASP.NET Core 2.0

I am not able to increase the session timeout in ASP.NET Core 2.0. Session gets expired after every 20 to 30 minutes. When I decrease the time to 1 minutes and debug it it works fine but when it is increased to more more than 30 minutes or hours/days it does not last to specified duration.

Session is expired after 30 minutes in debug mode as well as from IIS (Hosted after publish).

options.IdleTimeout = TimeSpan.FromMinutes(180);  

I am using below code in startup.cs file.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        
        // Adds a default in-memory implementation of IDistributedCache.
        services.AddDistributedMemoryCache();

        services.ConfigureApplicationCookie(options =>
        {
            options.Cookie.HttpOnly = true;
            options.Cookie.Expiration = TimeSpan.FromDays(3);
            options.ExpireTimeSpan= TimeSpan.FromDays(3);
            options.SlidingExpiration = true;
        });

        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromMinutes(180);                
        });
        services.AddSingleton<IConfiguration>(Configuration);
        
       
        // In production, the Angular files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IConfigurationSettings configurationSettings)
    {
       
        //
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseSession();
        app.UseStaticFiles();
        app.UseSpaStaticFiles();

        app.UseExceptionHandler(
         builder =>
         {
             builder.Run(
             async context =>
             {
                 context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                 context.Response.ContentType = "application/json";
                 var ex = context.Features.Get<IExceptionHandlerFeature>();
                 if (ex != null)
                 {                         
                     if(ex.Error is SessionTimeOutException)
                     {
                         context.Response.StatusCode = 333;
                     }
                     if (ex.Error is UnauthorizedAccessException)
                     {
                         context.Response.StatusCode =999;
                     }
                     var err = JsonConvert.SerializeObject(new Error()
                     {
                         Stacktrace = ex.Error.StackTrace,
                         Message = ex.Error.Message
                     });
                     await context.Response.Body.WriteAsync(Encoding.ASCII.GetBytes(err), 0, err.Length).ConfigureAwait(false);
                 }
             });
         });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");
        });

        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501

            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
            }
        });
    }
like image 327
Rupesh Kumar Avatar asked May 08 '18 07:05

Rupesh Kumar


People also ask

How do I increase my session timeout?

Click Servers > Server Type > WebSphere Application Servers > CongnosX_GW2. Click Container Settings > Session management > Set Timeout. Enter the desired timeout value in minutes. Click OK.

How do you handle session timeout?

Use some jquery that keys off of your session timeout variable in the web. config. You can use this Jquery delay trick that when a specific time occurs (x number of minutes after load of the page), it pops up a div stating session timeout in x minutes. Nice, clean and pretty simple.

Can you set the session out time manually?

Yes, we can set the session timeout manually in web. config. In ASP.NET we can set the session timeout in the web.

How to set session custom timeout in ASP NET MVC?

By default, the session timeout is 20 minutes after that session will expire. So if you want to increase or extend the session custom timeout for an application. You can set it in different ways such as using Web.config, Global.asax file, or using IIS. Here are some examples to set sessions custom timeout in ASP.NET or ASP.NET MVC.

How to increase the session timeout of a web application?

If you want to increase the session timeout then open your application web.config file which is placed under your application root folder. Add <sessionState timeout="300"></sessionState> code under <system.web> </system.web> the section as shown below, In this example, I have updated the timeout to 30 min

Is there a way to set request timeout in ASP NET Core?

No, there is not way to set request timeout in asp.net core hosted in IIS from C# code. But according to the documentation you can just add web.config to your project and specify this (and other) setting value: Setting the RequestTimeout="00:20:00" on the aspNetCore tag and deploying the site will cause it not to timeout.

How to use session state in ASP NET Core?

For using session state in an ASP.NET Core you need to add the session middleware to your pipeline. important: The order of middleware is the key. Call UseSession between UseRouting and UseEndpoints.


2 Answers

The issue might be coming because of your application pool get recycled on IIS. by default IIS Application pool get recycled after every 20 minutes.

Try to increase the application pool recycle time.

To change the application pool recycle time. Go through the following link

https://www.coreblox.com/blog/2014/12/iis7-application-pool-recycling-and-idle-time-out

like image 139
Trilok Kumar Avatar answered Oct 13 '22 14:10

Trilok Kumar


I work with asp.net core 2.2 (selfhosting in kestrel, without IIS) and had the same problem with some session variables (they were reset after about 20-30 minutes).

In startup.cs, I had:

services.AddSession();

(without options, as I tought a session lives automatically as long as the user have a connection)

I have changed this to:

services.AddSession(options =>
{
   options.IdleTimeout = TimeSpan.FromHours(8);
});

And... it seems to work (in Kestrel (production) and also with IIS-Express (Debugging)).

Regarding recycling (as mentioned above), according to this posting:

[Kestrel recycling:][1] Kestrel webserver for Asp.Net Core - does it recycle / reload after some time

It seems as Kestrel don’t recycle.

like image 2
FredyWenger Avatar answered Oct 13 '22 14:10

FredyWenger