How can I expire the session on clicking the browser back button in asp.net
asp.net, asp.net-mvc-4
Solution
This has been an issue for a while. Most people have used this to get around it :
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(Now.AddSeconds(-1));
Response.Cache.SetNoStore();
}
This code snippet basically directs the page in concern to expire immediately once it is posted and set the page to cache none of its content.
However, some browsers may ignore the page cache settings and some users may still get away with submitting a form multiple times.
Workaround :
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(Now.AddSeconds(-1));
Response.Cache.SetNoStore();
if (Page.IsPostBack){
if (isPageExpired()){
Response.Redirect("expired.htm");
}
else {
Session("TimeStamp") = Now.ToString;
ViewState("TimeStamp") = Now.ToString;
}
}
}
private boolean isPageExpired()
{
if (Session("TimeStamp") == null || ViewState("TimeStamp") == null)
return false;
else if (Session("TimeStamp") == ViewState("TimeStamp"))
return true;
else
return false;
}
Basically, whenever a page is loaded, it checks whether it is a resubmitted one by calling the isPageExpired function. If the function returns true, it redirects the page to the page-expired response; if not, it sets two timestamps: one saved in session state, the other view state.
The isPageExpired function compares the timestamp saved in session state and the timestamp in viewstate. If they are different, the user has submitted a form from cache; then, the page directs them to the Page-expired response.
Problem
This is my Scenario: I have the following pages: - 1 Login page - 1 Master Page as "ABC.Master" - 3 child pages as "page 1", "page 2", "page 3". The page 1, page 2 and page 3 are the child pages of Master Page "ABC.Master". Page flow : - After entering the Username and Password if I click on Login it moves to the Page 1 - From Page 1, if I click on some links, it moves to Page 2 - From Page 2, if I click on the Browser Back button, the Session should get expired Note: It should be purely like Banking website. i.e) On clicking the Browser back button the Session has to get expired.