views:

358

answers:

2

I am trying to create a background service in asp.net which checks for session timeouts and redirects the user to a timeout page ( not the login page ). My code is like this

public class SessionTimeoutModule : IHttpModule
{
    private static Timer timer;
    //Test value
    private const int interval = 1000 * 1 * 10;

    public void Init( HttpApplication application )
    {
        if ( timer == null )
        {
            timer = new Timer( new TimerCallback( CheckSessionTimeout ),
                         application.Context, 0, interval );
        }
    }

    private void CheckSessionTimeout( object sender )
    {
        HttpContext ctx = (HttpContext)sender;

        if ( ctx.Session != null && ctx.Session.IsNewSession )
        {
            var cookie = ctx.Request.Headers["Cookie"];
            if ( cookie != null )
            {
                if ( cookie.ToUpper().IndexOf( "ASP.NET_SESSIONID" ) >= 0 )
                {
                    ctx.Response.Redirect( "" );
                }
            }
        }
    }

    public void Dispose()
    {
        timer = null;
    }
}

The problem here is that i am not able to get the session value in the CheckSessionTimeout method. It is always null. How can get the Session here.

I have looked at this solution but it doesnt help.

A: 

I think there is a logical mistake here, even if you fix your code, you will never get an ended session.

if you can access to a session, it will have a sessionID. You can not get a session which ended by timeout by this way.

Maybe you should use global.asax's session_end. but I'm not sure it will help.

Also in here you can see, SessionID is not replaced until Session.Abandon.

Canavar
From what i have observed, when the session ends the IsNewSession property is set to true , thats the reason I have added the ctx.Session.IsNewSession check so that i can validate against it. Even with that, i think what csgero says is true. Anyways thanks for your reply
Vinay
+1  A: 

I'm afraid you are on the wrong track here. You cannot implement a background service an using an HttpModule like this. The HttpContext you are passing around is bound to an HTTP request, and I'm quite sure you should not keep it around like you're trying to do. Also even if you could detect the session time-out, there would be no way to redirect the user to a new page without an active request.
You might find this thread helpful.

csgero