Tutorial :Preventing an ASP.NET Session Timeout when using Silverlight


I'm writing a program which has both an ASP.NET configuration system and a Silverlight application. Most users will remain on the Silverlight page and not visit the ASP.NET site except for logging in, etc.

The problem is, I need the session to remain active for authentication purposes, but the session will timeout even if the user is using the features of the silverlight app.

Any ideas?


On the page hosting the silverlight control, you could setup a javascript timer and do an ajax call to an Http Handler (.ashx) every 5 minutes to keep the session alive. Be sure to have your Handler class implement IRequiresSessionState.

I recommend the Handler because it is easier to control the response text that is returned, and it is more lightweight then an aspx page.

You will also need to set the response cache properly to make sure that the browser makes the ajax call each time.


Here is the sample code for an HttpHandler

public class Ping : IHttpHandler, IRequiresSessionState  {      public void ProcessRequest(HttpContext context)      {          context.Response.Cache.SetCacheability(HttpCacheability.NoCache);          context.Response.ContentType = "text/plain";          context.Response.Write("OK");      }        public bool IsReusable      {          get { return true; }      }  }  

Then if you use jQuery, you can put this on your host aspx page

setInterval(ping, 5000);    function ping() {      $.get('/Ping.ashx');  }  

The interval is in milliseconds, so my sample will ping every 5 seconds, you probably want that to be a larger number. Fiddler is a great tool for debugging ajax calls, if you don't use it, start.


I've actually found a pretty cool hack which essentially embeds an iframe on the same page as the silverlight application. The iframe contains an aspx webpage which refreshes itself every (Session.Timeout - 1) minutes. This keeps the session alive for however long the silverlight app is open.

To do this:

Create an asp.net page called "KeepAlive.aspx". In the head section of that page, add this:

<meta id="MetaRefresh" http-equiv="refresh" content="18000;url=KeepAlive.aspx" runat="server" />        <script language="javascript" type="text/javascript">          window.status = "<%= WindowStatusText%>";      </script>  

In the code behind file, add this:

protected string WindowStatusText = "";        protected void Page_Load(object sender, EventArgs e)      {          if (User.Identity.IsAuthenticated)          {              // Refresh this page 60 seconds before session timeout, effectively resetting the session timeout counter.              MetaRefresh.Attributes["content"] = Convert.ToString((Session.Timeout * 60) - 60) + ";url=KeepAlive.aspx?q=" + DateTime.Now.Ticks;                WindowStatusText = "Last refresh " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();          }      }  

Now, on the same page as the silverlight app, add this:

<iframe id="KeepAliveFrame" src="KeepAlive.aspx" frameborder="0" width="0" height="0" runat="server" />  

Now the asp.net session will remain active while the silverlight app is being used!


The ajax ping / HttpHandler approach is good, but the JQuery $.get function is expecting a json result and throws a javascript parse error.

I modified the Ping HttpHandler to return "{}" instead of "OK" and this worked better.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »