asp.net计时器和response.redirect

时间:2010-12-08 06:43:28

标签: c# asp.net timer

我有一个Timer来检查某些条件,当条件成立时,它必须重定向页面

     protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            /* Thread th = new Thread(new ThreadStart(OtherThread));
             th.Start();*/
            System.Timers.Timer t = new System.Timers.Timer(9000);
            t.Enabled = true;
            t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
            Session["total"] = 0;
        }
    }  
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
if(db.getvalue()==true)
   response.redirect("abc.aspx"); //notworking
  //server.transfer("abc.aspx"); //not working
}

如何重定向我的网页。有什么方法可以通过js或其他任何方式完成吗?

3 个答案:

答案 0 :(得分:5)

发布页面后,发送重定向为时已晚:响应已经发送,因此您拥有的响应对象不再有效。

相反,您需要使用类似

的客户端脚本代码处理它
window.setTimeout(function() { window.location.href = "blah.aspx"; }, 9000);

或在响应中设置Refresh标头,告诉客户端当时需要加载不同的页面。

此外,从页面内部实例化Timer可能是一个坏主意 - 除了它持有无效的响应对象之外,即使访问者关闭页面,计时器也会挂起,并且就系统资源而言,它是一个相当昂贵的对象。

另一方面,如果您只想在后台检查该条件,请在global.asax事件的Application_OnStart中设置计时器,并让它更新volatile布尔变量;在要有条件重定向的页面开头检查此变量。

编辑:如果您希望在显示该页面的每个浏览器中为每个打开的窗口检查条件,则必须使用脚本或Refresh。让您的JavaScript间隔计时器定期尝试导航到一个特殊的“条件重定向器”页面可能是最简单的,该页面仅包含以下代码,该代码检查条件并重定向或单独保留页面:

<%
    if (db.getvalue())  // saying "== true" is redundant
        response.Redirect("abc.aspx");
    else
        response.StatusCode = HttpStatusCode.NoContent;
%>

请注意,导航到返回204“无内容”状态的URL会导致浏览器单独保留现有页面。此外,请记住,此重定向器页面将受到严重轰击,因此请保持您的检查轻量级。

答案 1 :(得分:0)

    <script language="javascript">
    function redirectFunction() {
        document.location.href = 'www.yourpage.com';
    }
    </script>
<body onload="javascript:setTimeout('redirectFunction();', 1000)"> 

然后在加载时,如果db.getvalue()= true,则可以处理逻辑,然后重定向到页面 为了避免整个页面刷新,请使用javascript进行一些google调用。

答案 2 :(得分:0)

 string myStringVariable = "Password Update!";
        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + myStringVariable + "');", true);

        Response.AddHeader("REFRESH", "1;URL=Login.aspx");