【问题标题】:How to Automatically Redirect if Session Expires? ASP.Net (From SessionTimeout.aspx to Timeout.aspx)如果会话过期,如何自动重定向? ASP.Net(从 SessionTimeout.aspx 到 Timeout.aspx)
【发布时间】:2018-04-03 02:48:03
【问题描述】:

我使用了 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();
        }

你们有什么解决方案,特别是 sn-ps 的建议来解决这个问题吗?我只是一个入门级程序员,不是高级程序员。

【问题讨论】:

标签: c# asp.net


【解决方案1】:

HTTP 是由客户端发起的无状态协议。所以不能使用Session过期来让页面自动Redirect到页面,但是可以尝试使用JssetInterval函数设置超时时间值和Sesssion.TimeOut一样模拟。

所以你可以通过DoRedirect 方法渲染一个JSDoRedirect 方法需要一个参数您的重定向页面名称。

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

【讨论】:

  • 澄清一下,我是否将其添加到 global.asax 中?因为当我在 asax 上添加这个时,就会出现这个错误。 ERR_TOO_MANY_REDIRECTS
  • 是的,您需要在 global.asax 上添加 Application_PostRequestHandlerExecute,我编辑我的答案:)
  • 仍然存在一个问题,虽然它重定向到 timeout.aspx 并且不再 ERR_TOO_MANY_REDIRECTS,但它不会等待 sessionstate timeout 超时。
  • 准确地说,当我运行 SessionTimeout.aspx 时,它会立即在 timeout.aspx 上重定向
  • 我明白了,你为什么不直接在SessionTimeout.aspx.cs Page_Load 上重定向到timeout.aspx,就像我的edit2 回答一样
猜你喜欢
  • 2015-08-17
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
  • 2017-10-28
  • 1970-01-01
  • 2016-08-09
  • 2021-06-07
  • 1970-01-01
相关资源
最近更新 更多