加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

如何在asp.net/c#中重现丢失的会话?

发布时间:2020-12-16 09:53:03 所属栏目:asp.Net 来源:网络整理
导读:我的问题是,有时我的会话会随机丢失,而有时它会起作用. 现在问题是,如果以某种方式可以重现会话(我的会话是当前登录的用户).我想也许我需要在我的母版页中更改一些内容,我现在只是检查会话是否失败,还是其他内容? 码: protected void Page_Load(object sen
我的问题是,有时我的会话会随机丢失,而有时它会起作用.

现在问题是,如果以某种方式可以重现会话(我的会话是当前登录的用户).我想也许我需要在我的母版页中更改一些内容,我现在只是检查会话是否失败,还是其他内容?

码:

protected void Page_Load(object sender,EventArgs e)
{
    if (Session["UserId"] == null)
    {
        Response.ClearContent();
        Response.Write("Not agine");
        Response.End();
    }
    else
    {
        Response.Write(Session["UserId"].ToString());
    }
}

Global.asax中

void Session_Start(object sender,EventArgs e) {
        // Code that runs when a new session is started
        if (HttpContext.Current.User != null && HttpContext.Current.User is HtUser)
        {

            HtUser user = (HtUser)HttpContext.Current.User;
            Session["UserId"] = user.UserId;
            if (user.HtDepartments.Any() && user.HtDepartments.SingleOrDefault().HtBusinessUnit != null)
            {
                int BusinessUnitId = user.HtDepartments.First().HtBusinessUnit.BusinessUnitId;
                Session["BusinessUnnitId"] = BusinessUnitId;
            }

在这里,您可以看到会话的代码

如果您需要更多东西,请告诉我!

感谢您的帮助和快速解答!

解决方法

如果我理解正确,用户会在会议结束时失去会话(超时).

为了防止这种情况,您可以在cookie中存储其他密钥(对于每个用户的user_id和unique_hash),然后在global.asax文件中编写一个方法,该文件将触发每个页面加载,并检查会话是否过期.如果是这样,方法将使用cookie密钥通过检查DB来恢复会话.

global.asax中的示例代码:

protected void Application_PreRequestHandlerExecute(object sender,EventArgs e)
{
    if (HttpContext.Current.Session != null)
    {
        // Restore session if session is lost but cookie is not
        // HttpContext.Current.Session["user_id"] == null &&
        if (HttpContext.Current.Request.Cookies["hash"] != null)
        {
            // do your job here
            RestoreSessionMethod();
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读