“如何检测会话超时并重定向到ASP.NET中的登录页面”

时间:2013-04-10 06:53:08

标签: asp.net asp.net-mvc c#-4.0

我在asp.net上有一个登录页面..如果成功登录,它会在下一页显示登录时间..那么如何编写一个通用函数来检测会话超时并重定向到login.aspx页面?这样我可以将其调用到所有其他页面

public partial class Login : System.Web.UI.Page
{
MainClass obj = new MainClass();

protected void bt_login_Click(object sender, EventArgs e)
{
    string s_name;

    SqlCommand cmd = new SqlCommand("select staff_id,staff_name from staff_details where staff_id='" + tb_loginid.Text + "' ", con);
    con.Open();

    SqlDataReader dr = cmd.ExecuteReader();
    if (dr.HasRows == true)
    {
        if (tb_password.Text == "ABCD" )
        {
            dr.Read();

            string id = dr[0].ToString();    
            s_name = dr[1].ToString();
            Session["staffname"] = s_name;
            Session["staffid"] = tb_loginid;

            String last_interaction_time = DateTime.Now.ToShortTimeString();
            Session["lasttime"] = last_interaction_time;
            Response.Redirect("Successfully_loggedin.aspx");
        }
    }
        else
        {  ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('Incorrect LoginID or Password!')", true);
            lb_invalid.Visible = true;
            tb_password.Text = "";
        }
}

}

和logged_in页面是

public partial class Successfully_logined : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

 string name=(string)Session["staffname"];
 lb_welcome.Text = "Welcome " + name+"!";

 string last_login_time= (string)Session["lasttime"];
 lb_logintime.Text =last_login_time;
}

}

和web.config是

<sessionState mode="InProc" cookieless="false" timeout="1">

1 个答案:

答案 0 :(得分:0)

为此您有检查条件..您也检查页面加载....

     if (Session["Username"] != null)
     { 
           // Code here 
     }
     else
     {
         Response.Redirect("login.aspx");
     }

详情请点击此处... Session_timeout