Session expiration in ASP.NET is a nasty problem. Imagine yourself filling a long form, hitting submit then boom you get the login page! That happened to me before and probably happened to you.
This problem doesn’t have an out-of-box solution in ASP.NET and there are different appraoches to solve it.
Increasing the session time out. Probably you are aware of the cons of this problem which are mainly consuming more server resources.
Having an image or an iframe that refreshes regularly and requests the server. This approach is a per page approach and you can select the pages to implement it on.
Personally, I’ve been using the second approach for a long time and didn’t have any problem with it. However, I made it more reusable, not to mention “cleaner”, by making it a web control.
If you are just interested in using the control then you can skip to the last section “Using the Control.”
Architecture
The architecture here is simple and consists of both server-side and client-side solutions.
Server-Side
An ASHX handler file hosted on the root of the site which when requested will renew the session and return a 1-pixel image. In my control, I called the ASXH file as session-keep-alive.ashx and this is the code:
Client-Side
On the client, my web control will render a 1-pixel image and some JavaScript code that will refresh the image every set amount of time from the ASXH file on the server. This is the control’s code:
And here is the used JavaScript, note that I am setting the Src of the image to
the same location (the ASHX file), but changing the query string to prevent the
browser from caching the request.
Using the JavaScript as an embedded resource
I have made the JavaScript file an embedded resource to make it easier for deployment. To do that I had to do the following:
Added a javascript file to the project library and called it JavaScript.js
I made this file an embedded resource by selecting it and setting Build Action to Embedded Resource
I have added the following line to the AssemblyInfo.cs : [assembly: WebResource("AT.Web.UI.Controls.JavaScript.js","application/x-javascript")]
Using the Control
Copy session-keep-alive.ashx to your website.
Reference AT.Web.UI.Controls.dll in your website.
You can add this control to the VS.NET toolbox OR you could add it manually by adding <%@ Register TagPrefix="at" Namespace="AT.Web.UI.Controls" Assembly="AT.Web.UI.Controls" %> to the top of the page and adding ``anywhere in the html body. You might need to set the refresh Duration, AutoHide or PageUrl