如果会话过期,如何自动重定向? ASP.Net(从SessionTimeout.aspx到Timeout.aspx)

时间:2018-04-03 02:48:03

标签: c# asp.net

我使用了Global.asax,这两个代码在会话超时后给我错误,例如:  '在此背景下无法提供响应。' - 如果我使用Response.Redirect  '对象引用未设置为对象的实例。' - 如果我使用HttpContext.Current.Response.Redirect

Global.asax中

 protected void Session_End(object sender, EventArgs e)
        {
            //HttpContext.Current.Response.Redirect("timeout.aspx");
            Response.Redirect("~/timeout.aspx");
        }

这是在我的Web.Config

的Web.Config

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <customErrors defaultRedirect="../error_page/" mode="Off"/>
    <sessionState timeout="1" cookieless="false" mode="InProc" ></sessionState>
  </system.web>
</configuration>

SessionTimeout.aspx.cs

 protected void Page_Load(object sender, EventArgs e)
        {
            Session["CustomSessionId"] = Guid.NewGuid();
        }

你们有没有任何解决方案,建议特别是片段来解决这个问题?我只是一名入门级程序员,而非先进程序员。

1 个答案:

答案 0 :(得分:1)

HTTP是由客户端发起的无状态协议。因此,您无法使用会话过期来允许页面自动Redirect到页面,但您可以尝试使用 Js setInterval函数设置超时时间与Sesssion.TimeOut相同的值来模拟。

因此,您可以通过DoRedirect方法呈现 JS DoRedirect方法需要您的重定向页面名称参数。

window.setInterval需要 MilliSeconds 时间来设置调用时间,因此您需要将60000乘以Session.Timeout

<强> SessionTimeout.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{

}

protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);
    DoRedirect("timeout.aspx");
}

public void DoRedirect(string page)
{
    int TimeOut = (this.Session.Timeout * 60000);
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.AppendLine("<script type='text/javascript'>");
    sb.AppendLine("window.setInterval('Redirect()'," +TimeOut.ToString() + @"); ");
    sb.AppendLine(" function Redirect(){ ");
    sb.AppendLine("window.location.href='/" + page + @"';");
    sb.AppendLine("}");
    sb.AppendLine(" </script>");

    ClientScript.RegisterClientScriptBlock(this.GetType(), "Redirect", sb.ToString());
}