Dipak Akhade February 2016

Manage user session in ASP.net

I am new in ASP.net and this is my first WebApp. I am facing problem in my App regarding session is that when I logout and press button back of browser it again pushes me in App. I am using code as below :

    protected void Page_Load(object sender, EventArgs e)
            {
                if (Session["LiveUser"] != null)
                {

                }
                else
                {
                    Response.Redirect("InvalidForm.aspx");
                }
            }


protected void ButtonLogOut_Click(object sender, EventArgs e)
        {
            Response.Redirect("LoginForm.aspx");
            Session["LiveUser"] = null;

        }

Button logout :

<asp:Button ID="ButtonLogOut" runat="server" CssClass="btnLogout"
                    Text="Log Out" OnClick="ButtonLogOut_Click" /> 

Login button code behind :

protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string query = "select UserActive from nWorksUser where Username='" + this.txtUsername.Text + "' and _password='" + Encrypt(this.txtPassword.Text) + "';";
            MySqlCommand cmd = new MySqlCommand(query, conn);
            MySqlDataReader rdr;
            conn.Open();
            rdr = cmd.ExecuteReader();
            string ActiveUser = "";
            while (rdr.Read())
            {
                ActiveUser = rdr.GetString("UserActive");
            }
            conn.Close();
            if (ActiveUser == "true")
            {
                if (trylogin(txtUsername.Text, txtPassword.Text) == true)
                {
                    Session.Add("LiveUser",GetUsername());
                    Response.Redirect("AttendanceForm.aspx");
                }
                else
                {
                    lableMessage.Text = "Wrong Credentials. Please try again";
                }
            }
            else
            {
                conn.Open        

Answers


Hrvoje Hudo February 2016

Logout click event should look more like this:

protected void ButtonLogOut_Click(object sender, EventArgs e)
{
    Session.Clear();
    Session.Abandon();
    Response.Redirect("LoginForm.aspx");
}

Redirect needs to be last.
Also, be aware, asp.net post back events (button clicks) are not browser back button friendly, since they will try to POST the form data again.
For log out, use regular a href link to a open signout page with GET method, or use post-redirect-get technique in case of post-back (Post-Redirect-Get with ASP.NET)

Post Status

Asked in February 2016
Viewed 3,956 times
Voted 14
Answered 1 times

Search




Leave an answer