imsanjaysc
imsanjaysc

Reputation: 101

Stop session from expiring when browser closes in MVC

I am facing a session issue After I close my browser my session expires, and after re-open browser, I have to log in again. I don't want to expire my session on browser close. I am using this in my web.config file:

 <authentication>
      <forms loginUrl="~/account/login" name="astroswamig" slidingExpiration="true" timeout="1000"></forms>
    </authentication>
    <sessionState mode="StateServer" cookieless="false" timeout="1000" />

and this in my controller:

string str = JsonConvert.SerializeObject(user);    
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.CustEmail, DateTime.Now, DateTime.Now.AddDays(120), true, str);
                        string enctryptTicket = FormsAuthentication.Encrypt(ticket);
                        HttpCookie authCustCookie = new HttpCookie(FormsAuthentication.FormsCookieName, enctryptTicket);
                        authCustCookie.Domain = "xyz.com";
                        Response.Cookies.Add(authCustCookie);

Upvotes: 3

Views: 982

Answers (1)

plr108
plr108

Reputation: 1205

The web.config sample in the question is using StateServer mode, so the out-of-process ASP.NET State Service is storing state information. You will need to configure the State Service; see an example of how to do that in the "STATESERVER MODE(OUTPROC MODE)" section here:

https://www.c-sharpcorner.com/UploadFile/484ad3/session-state-in-Asp-Net/

Also be sure to read the disadvantages section of the above linked article to make sure this approach is acceptable for your needs.

Another way to manage user session is using the InProc mode to manage sessions via a worker process. You can then get and set HttpSessionState properties as shown here:

https://www.c-sharpcorner.com/UploadFile/3d39b4/inproc-session-state-mode-in-Asp-Net/

and also here:

https://learn.microsoft.com/en-us/dotnet/api/system.web.sessionstate.httpsessionstate?view=netframework-4.8#examples

Again be sure to note the pros and cons of InProc mode in the above linked article to determine what approach best fits your needs.

Upvotes: 2

Related Questions