What is it all about?
This post shows you how to create a keep alive for a .NET website so people can stay logged in whilst the page is open, instead of it timing out after 20 minutes.
The basic premise to this is:
-
Create a handler which responds with an OK message and doesn't allow caching.
-
Add some javascript to the page to call the handler every 10 minutes.
-
The call to the server side handler keeps the session alive.
Here's how to do it:
-
Create a folder in your web project called
Handlers
, if you don't have one already.
-
Add a class called
KeepAlive.cs
-
Add the following code to the KeepAlive class
namespace CodeShare.Web.Handlers
public class KeepAlive : IHttpHandler, IRequiresSessionState
public void ProcessRequest(HttpContext context)
context.Response.AddHeader("Cache-Control", "no-cache");
context.Response.AddHeader("Pragma", "no-cache");
context.Response.ContentType = "text/plain";
context.Response.Write("OK");
public bool IsReusable { get { return false; } }
<handlers>
<remove name="KeepAlive" />
<add name="KeepAlive" verb="GET" path="<mark>keep-alive.ashx</mark>" type="CodeShare.Web.Handlers.KeepAlive " />
</handlers>
</system.webServer>
</configuration>
//calls the keep alive handler every 600,000 miliseconds, which is 10 minutes
var keepAlive = {
refresh: function () {
$.get('<mark>/keep-alive.ashx</mark>');
setTimeout(keepAlive.refresh, 6000000);
}; $(document).ready(keepAlive.refresh());