How does one discard a session variable while closing Web Page?

自闭症网瘾萝莉.ら 提交于 2019-12-13 17:06:51

问题


We are following a procedure in our work while developing a web page, is to bind page to one or more session variables, these session variables are used only for that page, to hold current processing objects, so while closing page no need for them.

How could I discard these session variables while closing page? Any suggestions regarding that technique or how to solve that problem?


回答1:


There is no server-side event that is raised when a page is left/closed. Also the Session_End event (mentioned in other answers) is not called when a page is left, since the user might navigate to other pages of the same web application (and therefore the session will continue to exist).

I can think of 3 possible ways to solve (or work around) this issue:

1 - use ViewState to store data with page-scope. This is what ViewState is made for, and unless you have a lot of data, it should not be a problem. If you have a lot of data, remember, that it will be serialized/deserialized and sent to the client/back to the server for every request (which may result in large requests and therefore bad performance).

2 - instead of putting the data into the session, put it into the Cache (with a low sliding expiration timeout). On your page, you can access your data in the same way as from the session, i.e. data = Cache["data"], but you have to be prepared that the data was removed from the Cache (you have to re-load it again from DB for example), if the time between two requests was bigger than the expiration time.

3 - use the client-side (javascript) onUnload event, and trigger some action (e.g. a ajax callback) to remove the data from the session. But I think the onUnload event is not reliable (it will not be fired in any case, e.g. when the browser is terminated by a crash or with the task manager, or if javascript is disabled).




回答2:


If you use variables for only that page, store them in viewstate. ViewState is suitable for page scoped variables.




回答3:


If you are using ASP.NET sessions (which you probably are), you can add a global.asax file to your soluting. In there this event-delegate is to be found (if not, create it):

protected void Session_End(object sender, EventArgs e)
{

}

.. In here you can clear your session collection.

    protected void Session_End(object sender, EventArgs e)
    {
        Session.Clear();
    }

This will be fired when the session expires or when a user clicks logout :)



来源:https://stackoverflow.com/questions/743447/how-does-one-discard-a-session-variable-while-closing-web-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!