简体   繁体   English

在Session_end事件上重定向到另一个页面

[英]Redirecting to another page on Session_end event

I would like to auto-redirect to login page when session time outs. 我希望在会话超时时自动重定向到登录页面。

In web.config file, i have the following code 在web.config文件中,我有以下代码

<configuration>
    <system.web>
       <sessionState mode="InProc"  timeout="1"/>
    </system.web>
</configuration>

In Global.asax file- 在Global.asax文件中 -

protected void Session_End(object sender, EventArgs e)
{
    Response.Redirect("LoginPage.aspx");
}

But after time-out, i am receiving the following error: 但超时后,我收到以下错误:

HttpException was unhandled by user code. HttpException未被用户代码处理。

Response is not available in this context. 在这种情况下无法获得响应。

Any clue to solve this issue? 有什么线索可以解决这个问题吗?

Session_End is called when the session ends - normally 20 minutes after the last request (for example if browser is inactive or closed). 会话结束时调用Session_End - 通常在最后一次请求后20分钟(例如,如果浏览器处于非活动状态或关闭状态)。
Since there is no request there is also no response. 由于没有请求,也没有回应。

I would recommend to do redirection in Application_AcquireRequestState if there is no active session. 如果没有活动会话,我建议在Application_AcquireRequestState进行重定向。 Remember to avoid loops by checking current url. 请记住通过检查当前URL来避免循环。

Edit: I'm no fan of .Nets built in authentication, Example goes in Global.asax : 编辑:我不喜欢.Nets内置身份验证,示例在Global.asax

    protected void Application_AcquireRequestState(object sender, EventArgs e)
    {
        try
        {
            string lcReqPath = Request.Path.ToLower();

            // Session is not stable in AcquireRequestState - Use Current.Session instead.
            System.Web.SessionState.HttpSessionState curSession = HttpContext.Current.Session;

            // If we do not have a OK Logon (remember Session["LogonOK"] = null; on logout, and set to true on logon.)
            //  and we are not already on loginpage, redirect.

            // note: on missing pages curSession is null, Test this without 'curSession == null || ' and catch exception.
            if (lcReqPath != "/loginpage.aspx" &&
                (curSession == null || curSession["LogonOK"] == null))
            {
                // Redirect nicely
                Context.Server.ClearError();
                Context.Response.AddHeader("Location", "/LoginPage.aspx");
                Context.Response.TrySkipIisCustomErrors = true;
                Context.Response.StatusCode = (int) System.Net.HttpStatusCode.Redirect;
                // End now end the current request so we dont leak.
                Context.Response.Output.Close();
                Context.Response.End();
                return;
            }
        }
        catch (Exception)
        {

            // todo: handle exceptions nicely!
        }
    }

If you are using something like FormsAuthentication for maintaining the security of your application, then this part (that part that you are trying to do) will be done for you. 如果您使用FormsAuthentication东西来维护应用程序的安全性,那么这部分(您尝试做的那部分)将为您完成。 If FormsAuthentication discovers that a user's session has expired it will redirect him or her back to you login page. 如果FormsAuthentication发现用户的会话已过期,则会将他或她重定向回您的登录页面。

Second, don't rely too much on Session_End because it will never trigger if you change session provider from InProc to SQLServer or other out of process provider. 其次,不要过多依赖Session_End因为如果将会话提供程序从InProc更改为SQLServer或其他进程外提供程序,它将永远不会触发

You can use session property IsNewSession to detect whether it is session timeout or not. 您可以使用会话属性IsNewSession来检测它是否是会话超时。

The ASP.NET HttpSessionState class has IsNewSession() method that returns true if a new session was created for this request. ASP.NET HttpSessionState类具有IsNewSession()方法,如果为此请求创建了新会话,则该方法返回true The key to detecting a session timeout is to also look for the ASP.NET_SessionId cookie in the request. 检测会话超时的关键是在请求中查找ASP.NET_SessionId cookie。

Definitely I too agree that we should put the below code in some so called a custom BasePage, which is used by all pages, to implement this effectively. 当然我也同意我们应该将下面的代码放在一些所谓的自定义BasePage中,所有的页面都使用它来有效地实现它。

override protected void OnInit(EventArgs e)
  {
       base.OnInit(e);   

if (Context.Session != null)
   {
if (Session.IsNewSession)
    {

     string CookieHeader = Request.Headers["Cookie"];
     if((CookieHeader!=null) && (CookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
     {
      // redirect to any page you need to
      Response.Redirect("sessionTimeout.aspx");
     } 
   }
 }
}

check this link for more explanations if you want to put the above code in a base page class . 如果要将上述代码放在基页类中,请查看此链接以获取更多说明。

You should use Application_AcquireRequestState You'll find that Application_AuthenticateRequest no longer has a session context (or never had one). 您应该使用Application_AcquireRequestState您将发现Application_AuthenticateRequest不再具有会话上下文(或从不具有会话上下文)。 In my research into this I cam across this post which solved it for me. 在我对此的研究中,我对这篇文章进行了解决,并为我解决了这个问题。 Thanks go to Waqas Raja. 谢谢你去Waqas Raja。

asp.net: where to put code to redirect users without a session to the homepage? asp.net:在没有会话的情况下将代码重定向到主页的位置?

I think you are getting "Response is not available in this context" because the user is not making a request to the server, and therefor you cannot provide it with a response. 我认为你得到“响应在这种情况下不可用”,因为用户没有向服务器发出请求,因此你无法为它提供响应。 Try Server.Transfer instead. 请尝试使用Server.Transfer。

The easiest way what I feel is to use Meta information and get the trick working. 我觉得最简单的方法就是使用Meta信息并使技巧发挥作用。 Consider we have a page WebPage.aspx add the below code in the the WebPage.aspx.cs file. 考虑我们有一个页面WebPage.aspxWebPage.aspx.cs文件中添加以下代码。

private void Page_Load(object sender, System.EventArgs e){      
    Response.AddHeader("Refresh",Convert.ToString((Session.Timeout * 60) + 5));      
    if(Session[“IsUserValid”].ToString()==””)              
    Server.Transfer(“Relogin.aspx”);
}

In the above code, The WebPage.aspx is refreshed after 5 seconds once the Session is expired. 在上面的代码中,一旦Session过期, WebPage.aspx会在5秒后刷新。 And in the page load the session is validated, as the session is no more valid. 并且在页面加载中会话被验证,因为会话不再有效。 The page is redirected to the Re-Login page. 该页面将重定向到“重新登录”页面。 Every post-back to the server will refresh the session and the same will be updated in the Meta information of the WebPage.aspx . 每次回发到服务器都会刷新会话,同样会在WebPage.aspx的元信息中WebPage.aspx

you can simply do the following in web.config 您只需在web.config中执行以下操作即可

<configuration>
<system.web>
<sessionState mode="InProc"  timeout="1" loginurl="destinationurl"/>
</system.web>
</configuration>

Since, we can't redirect from Session_End as no response/redirect is present there.By using this you will be redirected to destinationurl when session will timeout.Hope this helps. 因为,我们无法从Session_End重定向,因为那里没有响应/重定向。通过使用它,当会话超时时,您将被重定向到destinationurl。希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM