ASP.NET Page Life Cycle Issues

1.8k Views Asked by At

Apparently I am not familiar with the Life Cycle of a page in ASP.NET. This became apparent when I wanted to dispose of a Session variable after I left the page. I did what made the most sense:

    protected void Page_Unload(object sender, EventArgs e)
    {
        Session.Remove("ServiceSearch");
    }

What I didn't know is that this would be called when I go from AND to the page. What I am wanting to do is dispose of that Session variable whenever the user leaves the page. How do I do this?

4

There are 4 best solutions below

0
On BEST ANSWER

Page_Unload refers to unloading the Page object right before it is disposed after parsing and creating the page. It has nothing to do with leaving the page. Like @Nick says, there is really no good way to tell that, except to control every exit path. And you can't, because you can't control when the user hits back, or goes to google.com and then pastes in the url they were just at into the browser, etc.

If you want to remove the Session variable just so it doesn't get re-used unintentionally, a better solution is to overwrite the Session variable every time you enter the page, and just let it be disposed with the session on its own time when the session expires.

0
On

Session data is useful for storing data beyond the lifetime of a page. If you don't want to store it beyond the life of a page then Session data is not for you here.

0
On

If the user leaves the page via a link you could possibly create a link button that is hooked up to a method on the same page. That method would remove the session and do the redirect.

I would hope there is a better solution though. Although, from my understand, there is no page event to use in your case because the page would have to reload to execute the remove session code. When the user leaves via some link the page is not reloaded.

You may possibly be able to handle it via javascript. I've been in situations where I wanted to leave and I got a popup box about some bs. You could probably use the same technique to fire AJAX to remove the session.

0
On

I faced a similar situation on php login- a logged-in user could use the arrow back and forth to login page. So, I simply add :

session_start();
session_unset();
session_destroy();

above the html script of the login page so that if the logged-in user arrowed back, the session is both unset and destroyed. Any attempt to arrow forward will only lead to the login page-requesting user login credentials-essentially, the user is logged out any time they arrow back! Hope this helps!

Alfred