how to logout the user from my asp.net application?

MrClan picture MrClan · Mar 8, 2012 · Viewed 13.2k times · Source

I'm using custom code to login and logout the user in my web application. on click of the login button, the code below executes:

if (Membership.ValidateUser(txtUserEmail.Text, txtUserPass.Text))
{
    HttpContext.Current.Profile.Initialize(txtUserEmail.Text.Trim(), true);
}

I then check the profile.Username on pre-init of everypage to check whether the user is logged in or not. But now I don't know what to do to logout the user, so that the profile is set to null or something. I'm trying all of these on the click of the logout button :

protected void lnkBtnLogout_Click(object sender, EventArgs e)
{
Session.Abandon();
Request.Cookies.Clear();
FormsAuthentication.SignOut();
var p = HttpContext.Current.Profile;
Response.Redirect("/Default.aspx");
}

I'm using variable p just to check whether the profile has been reset or not, but it still has all the values of the logged in user. So, what should I do to reset the profile and logout the user???

Answer

Aristos picture Aristos · Mar 8, 2012

Right after the SignOut() make a redirect with stop anything else, so the page stop update anything else.

So the code will be.

protected void lnkBtnLogout_Click(object sender, EventArgs e)
{
  Session.Abandon();
  Request.Cookies.Clear();
  FormsAuthentication.SignOut();
  Response.Redirect("/Default.aspx", true);
}

After the redirect check if the use is still log in. The user is not log out after the call of SignOut, but after the end and flush of the final cookie, and on the next page load.