Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 995
Russell Patterson Avatar asked Jun 30 '09 21:06

Russell Patterson


1 Answers

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.

UPDATE

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.

like image 175
NerdFury Avatar answered Sep 21 '22 17:09

NerdFury