aleczandru
aleczandru

Reputation: 5459

Session_OnEnd behavior

Hi I am not very familiar with how asp.net SESSIONS work but after some reading I found that it could help me solve a problem that I have without much effort.

My problem is related to a situation where a user is allowed to upload some documents on the server but not actually save them in the database until he presses the post button.

If he uploads the documents and closes the browser the documents remain on the fileSystem and there is no way of knowing what documents were saved there.

In order to solve this problem I decided to store the details of the document in the session , but not the actual document which is saved on the fileSystem.

When the page first load a clean up of the fileSystem is executed based on the data stored in the session.

Now the only thing that remains is being able to handle the case of the user closing the browser and the session expiring in the meantime.

After some research I found that when the session expires even if the browser closes the Session_OnEnd method is runes , so I added my code here:

 public void Session_OnEnd()
 {
    var session = Session[Constants.FILE_SHARE_DOCUMENT];
    if (session != null)
    {
        var documents = (List<Document>)session;
        foreach (var document in documents)
        {
            string filePath = Path.Combine(Constants.SERVER_PATH, document.StorageFileName);
            File.Delete(filePath);
        }
    }
}

I have also set the session end to 1 min and it seems to work in all the cases I have tryed.

Can anyone confirm if this is a reliable way of solving my problem?

Is there anything I am missing?

Upvotes: 0

Views: 593

Answers (1)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93464

This is not a reliable mechanism for a number of reasons.

First, setting session to 1 minute? That's not very long.. You really want users that pause for a minute to have their session end? Of do you mean you set it to 1 minute in order to test? Typically session timeout is more like 20 minutes.

Second, Session_End will not get called in cases where the worker process is recycled. That can be, if the worker process crashes, is setup to recycle on a schedule, or is manually recycled.

I would simply have your cleanup process delete all files that have a timestamp greater than a certain time. It's simple and easy.

Upvotes: 2

Related Questions