Home > Net >  ASP.NET Core - How to restart session timeout programatically
ASP.NET Core - How to restart session timeout programatically

Time:04-04

I'm migrating a .NET 4 Framework ASP.NET MVC project to .NET Core and I have the following controller method (.NET 4):

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] // Never Cache
public virtual ActionResult Extend()
{
     // Re-establish the session timeout
     Session.Timeout = Utility.Constants.sessionTimout;
     return new EmptyResult();
}

This is my code in .NET Core

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
//[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] // Never Cache
public virtual ActionResult Extend()
{
    // Re-establish the session timeout
    // TODO: Need to find out in ASP.NET CORE
    
    //this.HttpContext.SessionSession.Timeout = Utility.Constants.sessionTimout;
    return new EmptyResult();
}

I have been trying to find out how to do Session.Timeout in .NET Core but haven't been lucky.

** UPDATE ** This method restarts timeout from an external application that is loaded into an IFrame. So when user is in the iFrame app, the main ASP.NET application is not getting any interaction at all. So that's why I require to extend the session timeout manually from the iFrame app.

Any clue?

CodePudding user response:

I am not familiar with the TimeOut property being available in .net core.

But, it is possible to use Session state as described here

You can set the timeout during setup:

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromSeconds(10);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

A call to your Extend action should be sufficient to reset the idle timers.

Keep in mind, accessing the Session state is different in .net core, e.g.:

HttpContext.Session.SetString("foo", "bar");
string foo = HttpContext.Session.GetString("foo");

Typically, even within the IFrame, the using interacting with the page should be sufficient to reset the IdleTimeout.

As @Aria you can even detect the upcoming timeout and act accordingly.

  • Related