在asp.net中存储会话数据mvc
问题描述:
我在我的应用程序中使用Session
来存储一些数据,如用户名(写hello,...)等等。另外,我使用FormsAuthentication
验证用户,所以控制器有这样的代码:在asp.net中存储会话数据mvc
protected void SetAuthCookie(int userId)
{
FormsAuthentication.SetAuthCookie(userId.ToString(), true);
User user = Repositories.UserRepository.GetUserById(userId);
Session["name"] = user.Name;
Session["email"] = user.Email;
Session["balance"] = user.TotalBalance + "/" + user.ActiveBalance;
Session["isConfirmed"] = user.IsConfirmed;
Session["phone"] = user.Phone;
}
所以,当我的一些代码后重新启动应用程序改变会话数据被破坏,但用户通过身份认证,所以我有很不好的情况,我想解决它。一方面,我可以在某处创建代码,这将检查会话数据是否正常,否则刷新它。另一方面,我可能会错过一些以正确的方式存储这些数据的技术吗?
在这种情况下最好的解决方案是什么?
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
答
我也有过类似的问题解决了像这样的的global.asax.cs文件:它会强制注销如果会话是空的,并且请求进行身份验证。 (将您的会话值之一始终设置为检查为空)
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
ForceLogoutIfSessionExpired();
}
private void ForceLogoutIfSessionExpired()
{
if (Context.Handler is IRequiresSessionState)
{
if (Request.IsAuthenticated)
{
if (HttpContext.Current.Session["name"] == null)
{
AuthenticationHandler.SignOut(Response);
Response.Redirect(FormsAuthentication.LoginUrl, true);
}
}
}
Cookie在会话中持续存在。这里有什么问题?当您检测到cookie时,请设置会话值。 – DLeh 2014-11-03 13:24:08
另外,使用会话不建议与MVC。 MVC意味着尽可能无状态,依靠会话将打破这一点。 – DLeh 2014-11-03 13:25:15
有时,用户通过身份验证,但会话数据不再存在。发生这种情况,当我在代码更改后重新启动应用程序时,在其他情况下我害怕这种情况 – lenden 2014-11-03 13:25:41