will httpcontext.session stay active if read?

480 views Asked by At

I know that Httpcontext.Session in MVC C# has a default timeout period of 20minutes.

But what if is read every 10minutes? Will this extend the timeout period? Or will it still time out after 20mins even if it is read within the 20minutes?

and part 2#. assuming the httpcontext will not time out if it is read within the timeout period, Is it ok to store a dbcontext in a httpcontext.session?

code like this:

public GenericDal()
{
    if (HttpContext.Current.Session["unitOfWorks"] == null)
    {
        unitOfWorks = new UnitOfWork();
        HttpContext.Current.Session.Add("unitOfWorks", unitOfWorks);
    }
    else
    {
        unitOfWorks = (UnitOfWork)HttpContext.Current.Session["unitOfWorks"];
    }

}
1

There are 1 answers

0
Jamie Burns On

It uses a sliding expiration, so when you access it, the timeout gets extended.

A session is considered active as long as requests continue to be made with the same SessionID value. If the time between requests for a particular session exceeds the specified time-out value in minutes, the session is considered expired. Requests made with an expired SessionID value result in a new session.

https://msdn.microsoft.com/en-us/library/vstudio/ms178581(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

And I wouldn't put the context in the session. The discussion about DBContext in the session is well documented -

One DbContext per web request... why?