当浏览器在 MVC 中关闭时停止会话过期

Stop session from expiring when browser closes in MVC

我遇到会话问题关闭浏览器后我的会话过期,重新打开浏览器后,我必须重新登录。 我不想在浏览器关闭时使我的会话过期。 我在我的 web.config 文件中使用它:

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

这在我的控制器中:

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);

问题中的web.config样本使用的是StateServer模式,所以进程外ASP.NETState Service正在存储状态信息。您将需要配置状态服务;在此处的 "STATESERVER MODE(OUTPROC MODE)" 部分查看如何执行此操作的示例:

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

另请务必阅读以上链接文章的缺点部分,以确保此方法可以满足您的需求。

管理用户会话的另一种方法是使用 InProc 模式通过工作进程管理会话。然后,您可以获取并设置 HttpSessionState 属性,如下所示:

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

还有这里:

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

再次务必注意上面链接文章中 InProc 模式的优缺点,以确定哪种方法最适合您的需求。