Reputation: 25
I am wondering how to log out the user from a session in C# using ASP.NET. I am using SQL Server to retrive the users name for when they are logged in, (2nd block of code below) Directly below here is my code behind for my login button from my aspx page
protected void btnLogin_Click(object sender, EventArgs e)
{
string email = txtEmail.Text;
string password = txtPassword.Text;//AQUIRE EMAIL AND PASSWORD AND ADD TO STRINGS
SqlDataReader dataread = null;
SQLconn.Open();
SqlCommand chkLogin = new SqlCommand("SELECT * FROM Member WHERE Email='" + email + "' AND Password='" + password + "'", SQLconn);
dataread = chkLogin.ExecuteReader();
SqlCommand nameAdd = new SqlCommand("SELECT Name FROM Member WHERE Email='" + email + "'", SQLconn);
if (dataread.Read())
{
Response.Write("You are logged in");
Session.Add("userID", dataread[0].ToString());
Session.Add("userFName", dataread[1].ToString());
Session.Add("userEmail", dataread[3].ToString());
Response.Redirect("~/Profiles.aspx");
}
else
{
Response.Write("Please try again. Usernames and Passwords do not match.");
}
SQLconn.Close();
}
When they are logged in they are redirected to another page. Here is the code behind for that page
if (Session.Count > 0)
{
if (Session.Count > 0)
{
string name = (string)Session["userFName"];
txtGreeting.Visible = true;
txtGreeting.Text = "Welcome " + name + " , you are logged in! ";
}
}
Upvotes: 0
Views: 3915
Reputation: 169
You can use Session.Clear(); method when user clicks on Logout button if you have one.
And on your this method
if (Session.Count > 0)
{
if (Session["username"] != null)
{
string name = (string)Session["userFName"];
txtGreeting.Visible = true;
txtGreeting.Text = "Welcome " + name + " , you are logged in! ";
}
else{
Response.Redirect(Logout.aspx);
}
}
add one more condition to check whether the Session has something or not.
Upvotes: 0
Reputation: 2602
The way you are using session for logging in/out is not correct but with that said if you are just trying to remove the user when log out is clicked do this:
Session["userFName"] = null; //the other session vars related to user as well
Suggestion: Look into forms authentication at a minimum or possibly token authentication. Session can be hijacked and you are opening your application to attack.
Upvotes: -1