检测 ASP.NET MVC 上的会话过期

发布于 2024-08-07 00:02:03 字数 504 浏览 5 评论 0原文

我构建了一个购物车,它使用会话状态在用户浏览商店时保留购物车数据。

我遇到一个问题,如果我在购物车的第 1 步上长时间打开浏览器窗口,然后按“转到第 2 步”,我的操作会引发错误,因为第 2 步操作假定会话尚未过期,并且ShopCart 对象处于正确状态。

我希望这种情况对我的用户来说更好,但我认为我需要以某种方式检测会话是否已过期,以便在下一个请求时我可以将它们扔到第 1 步。

我发现下面的代码声称可以解决问题,但它对我不起作用。

IsNewSession 条件为 true,但该条件

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

始终返回 false,并且从不处理无效会话。我很困惑。

这在 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.

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.

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

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

与君绝 2024-08-14 00:02:03

方式 1

将此代码放在 Page 2 的 Init / Load 事件中...

        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

或者,您可以检查之前的 Session 对象是否存在继续在第 2 页中使用它,如下所示:

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

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

Way 2

Alternative you can check whether the Session object exists before proceeding to work with it in Page 2, like this:

if (Session["Key"] != null)
{
   Object O1 = (Object) Session["Key"]; 
}
else
{
    Response.Redirect("ErrorPage.aspx");
}
荒路情人 2024-08-14 00:02:03

国王的回答对我不起作用。我在 OnActionExcuting() 中添加了 FormsAuthentication.SignOut()Response.Redirect 将不起作用!

if (Request.IsAuthenticated)
{
    FormsAuthentication.SignOut();
}

这是我完整的方法

public class SessionExpireFilterAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;

            // check if session is supported
            if (ctx.Session != null)
            {

                // check if a new session id was generated
                if (ctx.Session.IsNewSession)
                {

                    // If it says it is a new session, but an existing cookie exists, then it must
                    // have timed out
                    string sessionCookie = ctx.Request.Headers["Cookie"];
                    if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                    {
                        string redirectOnSuccess = filterContext.HttpContext.Request.Url.PathAndQuery;
                        string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
                        string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
                        if (ctx.Request.IsAuthenticated)
                        {
                            FormsAuthentication.SignOut();
                        }
                        RedirectResult rr = new RedirectResult(loginUrl);
                        filterContext.Result = rr;
                        //ctx.Response.Redirect("~/Home/Logon");

                    }
                }
            }

            base.OnActionExecuting(filterContext);
        }
    }

The King 's answer does not work for me. I have added FormsAuthentication.SignOut() in OnActionExcuting(). The Response.Redirect will not work!

if (Request.IsAuthenticated)
{
    FormsAuthentication.SignOut();
}

This is my complete method

public class SessionExpireFilterAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;

            // check if session is supported
            if (ctx.Session != null)
            {

                // check if a new session id was generated
                if (ctx.Session.IsNewSession)
                {

                    // If it says it is a new session, but an existing cookie exists, then it must
                    // have timed out
                    string sessionCookie = ctx.Request.Headers["Cookie"];
                    if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                    {
                        string redirectOnSuccess = filterContext.HttpContext.Request.Url.PathAndQuery;
                        string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
                        string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
                        if (ctx.Request.IsAuthenticated)
                        {
                            FormsAuthentication.SignOut();
                        }
                        RedirectResult rr = new RedirectResult(loginUrl);
                        filterContext.Result = rr;
                        //ctx.Response.Redirect("~/Home/Logon");

                    }
                }
            }

            base.OnActionExecuting(filterContext);
        }
    }
暖伴 2024-08-14 00:02:03

您需要在项目的 Global.asax.cs 文件中创建 Session_OnEnd 方法。

这是我的代码,我能够检测 ASP.NET MVC 上的会话过期

protected void Session_OnEnd(object sender, EventArgs e)
{
    int userid = 0;
    userid = Convert.ToInt32(Session["UserID"]);
    if (userid != 0)
    {
        var userActivity = DependencyResolver.Current.GetService<IUserRepo>();
        var responce = userActivity.LogOutUsers(userid);
        if (responce == true)
        {
            Session.Clear();
            Session.Abandon();
        }
    }
}

更多

You need to create the Session_OnEnd method In Global.asax.cs file in your project.

this is my code and I am able to Detecting Session expiry on ASP.NET MVC

protected void Session_OnEnd(object sender, EventArgs e)
{
    int userid = 0;
    userid = Convert.ToInt32(Session["UserID"]);
    if (userid != 0)
    {
        var userActivity = DependencyResolver.Current.GetService<IUserRepo>();
        var responce = userActivity.LogOutUsers(userid);
        if (responce == true)
        {
            Session.Clear();
            Session.Abandon();
        }
    }
}

more

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文