session timeout on ajax call session timeout on ajax call ajax ajax

session timeout on ajax call


A 403 status code is going to cause jQuery to call the failure method. Keep the same code behind from your second try, but move the redirect handler to the failure method instead of the success method. In the success method, treat it as you normally would.


Problem:

I had same problem in my Razor MVC Application throwing exceptions while ajax calls made when session timed out.

The way I have managed to get this issue sorted is by monitoring each ajax requests by using a simple light weight Action Method (RAZOR MVC) returning a bool variable whether the Request is Authenticated or not. Please find the code below..

Layout/Master Page / Script file:

<script>var AuthenticationUrl = '/Home/GetRequestAuthentication';var RedirectUrl = '/Account/Logon';function SetAuthenticationURL(url) {AuthenticationUrl = url;}function RedirectToLoginPage() {window.location = RedirectUrl; } $(document).ajaxStart(function () { $.ajax({    url: AuthenticationUrl,    type: "GET",    success: function (result) {        if (result == false) {            alert("Your Session has expired.Please wait while redirecting you to login page.");            setTimeout('RedirectToLoginPage()', 1000);        }    },    error: function (data) { debugger; }});

})

Then in Home Controller/Server side you need a method to verify the request and return the boolean variable..

    public ActionResult GetAuthentication ( )    {        return Json(Request.IsAuthenticated, JsonRequestBehavior.AllowGet);    }

This will validate each ajax request and if the session got expired for any ajax request, it will alert the user with a message and redirect the user to the login page.

I would also suggest not to use standard Alert to Alert. User some Tool tip kind of formatted div Alerts. Standard JS Alerts might force the user to click OK before redirection.

Hope it helps.. :)

Thanks,Riyaz


Finally, I ended up following.

public class IsAuthorizedAttribute : ActionFilterAttribute    {        public override void OnActionExecuting(ActionExecutingContext filterContext)        {            if (filterContext.HttpContext.Request.IsAjaxRequest())            {                var sessions = filterContext.HttpContext.Session;                if (sessions["User"] != null)                {                    return;                }                else                {                    filterContext.Result = new JsonResult                    {                        Data = new                        {                            status = "401"                        },                        JsonRequestBehavior = JsonRequestBehavior.AllowGet                    };                    //xhr status code 401 to redirect                    filterContext.HttpContext.Response.StatusCode = 401;                    return;                }            }            var session = filterContext.HttpContext.Session;            if (session["User"] != null)                return;            //Redirect to login page.            var redirectTarget = new RouteValueDictionary { { "action", "LogOn" }, { "controller", "Account" } };            filterContext.Result = new RedirectToRouteResult(redirectTarget);        }    }

Handling client side

<script type="text/javascript">    $(document).ajaxComplete(       function (event, xhr, settings) {           if (xhr.status == 401) {               window.location.href = "/Account/LogOn";           }    });</script>