在ASP.NET MVC检测会话过期 [英] Detecting Session expiry on ASP.NET MVC

查看:135
本文介绍了在ASP.NET MVC检测会话过期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个使用会话状态保持的购物车数据,而用户正在浏览的商店购物车。

I have built a shopping cart that uses Session State to keep the shopping cart data while the user is browsing the store.

我有一个问题,如果我离开浏览器窗口打开很长一段时间对购物车的第一步,那么preSS转到步骤2,因为第二步操作假设会话我的行动会引发错误还没有过期,且询对象处于正确的状态。

I have an issue where if I leave the browser window open for a long time on step1 of the shopping cart, then press "go to step 2", my actions throw an error because the step2 action assumes the session hasn't expired and the ShopCart object is in the correct state.

我想这种情况下是为我的用户更好,但我想我需要以某种方式检测,如果会话已过期,这样在下次请求我可以将它们扔到第一步。

I would like this scenario to be nicer for my users, but I think i need to somehow detect if the session has expired so that on next request I can throw them to Step1.

我发现下面的code,声称要解决的问题,但它不为我工作。

I found the following code that claims to to solve the problem, but it doesn't work for me.

该IsNewSession条件为真,但条件

The IsNewSession condition is true but the condition

if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) {
   // handle expired session
}

总是返回假,它永远不会处理无效的会话。我很困惑。

always returns false and it never handles the invalid session. I'm confused.

这是可能在ASP.NET(和MVC)?

Is this possible in ASP.NET (and MVC)?

推荐答案

放入初始化 / 加载此code 第2页的事件......

Way 1

Put this code in the Init / Load event of Page 2...

        if (Context.Session != null)
        {
            if (Context.Session.IsNewSession)
            {
                string sCookieHeader = Request.Headers["Cookie"];
                if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
                {

                    if (Request.IsAuthenticated)
                    {
                        FormsAuthentication.SignOut();
                    }
                    Response.Redirect("Error Page");
                }
            }
        }

路2

替代,您可以检查在继续第2页与它的工作,就像在此之前是否存在会话对象:

if (Session["Key"] != null)
{
   Object O1 = (Object) Session["Key"]; 
}
else
{
    Response.Redirect("ErrorPage.aspx");
}

这篇关于在ASP.NET MVC检测会话过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆