Saving contents of ApplicationState in ASP.Net (MVC)

547 views Asked by At

I have an internal app used to edit XML files on disk. The XML files are loaded into an object model which is stored in ApplicationState.

I need to save this data. The one option is to do this every time the user changes some data. However, this seems a bit inefficient - writing the data out to disk each time a change is made.

Instead, is it possible to be notified whenever the user closes their browser, plus just before the web server exits? Thus, the data would be saved each time a session ends, plus when the computer shuts down, etc. I thought that Application_End(), Application_Error() and Session_End() in Global.asax would provide this, but these methods don't seem to be called.

1

There are 1 answers

4
Liam On

Session_End should get called.

What version of IIS are you running on, or are you hosting in the Visual Studio development server?

Steps to get Session_End to fire:

  1. Create a new web site in VS 2008

  2. Edit web.config:

    Add <sessionState mode="InProc" cookieless="true" timeout="1"/> to <system.web>

  3. Add a Global.asax file with the code shown below.

    void Session_End(object sender, EventArgs e)

    {

    Console.WriteLine( "Session_End" );

    }

  4. Set a breakpoint on the Console.WriteLine call.

  5. Press F5 and see the page load in IE or Firefox.

  6. Wait 1 minute or so.

  7. The breakpoint should be highlighted in red in the IDE.