Thursday, August 11, 2011

How to prevent visiting pages from History after Logout


After having successfully logged-in to an application, you are redirected to the next page (say Home.aspx) which is a content page of master page (say Master.master). In this master page you have a link for logout. When you click on the logout button it redirects you to the Login page (provided this is not the content page of Master.master). Now if you click on the back arrow of browser then it goes to the previous page. To avoid this, the following code can be used in your master page where the logout button is present.
 Design a login page, give user name and password then redirect to some other page which is a content page of a Master page. In this master page one link button should be present for logout. When you click on the logout button it redirects to the login page. Then when you click on the back arrow of the browser it again goes to the previous page (that you already visit before logout). Even if you write code for session clear in logout button click event still it goes to previous page. To avoid this write few lines of code in Page_Init method of master page.
  protected void Page_Init(object sender, EventArgs e)
{
      Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
      Response.Cache.SetCacheability(HttpCacheability.NoCache);
      Response.Cache.SetNoStore();
}
 
 
Following is the full code for master page where logout button is present.
Master.master
<asp:LinkButton ID="lnkLogout" runat="server" Text="logout"onclick="lnkLogout_Click"></asp:LinkButton>
Master.master.cs
protected void Page_Init(object sender, EventArgs e)
{
      Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
      Response.Cache.SetCacheability(HttpCacheability.NoCache);
      Response.Cache.SetNoStore();
}
protected void Page_Load(object sender, EventArgs e)
{
      long userId = Convert.ToInt64(Session["UserId"]);
      if(!IsPostBack)
      {
            if(userId == 0)
            {
                  Response.Redirect("Login.aspx");
            }
      }
}
protected void lnkLogout_Click(object sender, EventArgs e)
{
      Session.Clear();
      Session.Abandon();
      Response.Redirect("Login.aspx");
 
}
 
N.B:- Login page was not a content page of Master page (which contains the logout button).

No comments: