Posted: December 2nd, 2008 | Author: YuSuF | Filed under: Programming | Tags: ajax, asp.net, httpmodule, session-timeout | No Comments »
You can use the following code as an http module.
It detects if the request is an ajax request and checks for validity of session and redirects to login page if session has timed out.
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
namespace myWeb.Library
{
public class AjaxTimeOutHandler : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
throw new NotImplementedException();
}
public void Init(HttpApplication context)
{
context.BeginRequest += context_BeginRequest;
}
void context_BeginRequest(object sender, EventArgs e)
{
var httpApp = (HttpApplication)sender;
var context = httpApp.Context;
bool isTimeout = false;
HttpCookie authCookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket authTicket = null;
if (authCookie == null)
{
isTimeout = true;
}
else
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket.Expired)
{
isTimeout = true;
}
}
if (context.Request.IsAjaxCallBack() && isTimeout)
{
context.Response.Redirect(FormsAuthentication.LoginUrl + "?ReturnUrl=" + HttpUtility.UrlEncode(context.Request.RawUrl));
}
}
#endregion
}
}
Leave a Reply