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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1490879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:03:44  来源:igfitidea点击:

Detecting Session expiry on ASP.NET MVC

c#asp.netasp.net-mvcsessionsession-state

提问by CVertex

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.

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

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.

我希望这个场景对我的用户更好,但我认为我需要以某种方式检测会话是否已过期,以便在下一个请求时我可以将它们扔到 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

IsNewSession 条件为真,但条件

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.

总是返回 false 并且它从不处理无效的会话。我糊涂了。

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

这在 ASP.NET(和 MVC)中可行吗?

采纳答案by The King

Way 1

方式一

Put this code in the Init/ Loadevent of Page 2...

将此代码放在第 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");
                }
            }
        }

Way 2

方式二

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

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

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

回答by Tom

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

国王的回答对我不起作用。我已经添加FormsAuthentication.SignOut()OnActionExcuting(). 本Response.Redirect都不行!

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

回答by Sandip Kalsariya

You need to create the Session_OnEndmethod In Global.asax.csfile in your project.

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

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

这是我的代码,我能够在 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

更多的