Handling session timeout in ajax calls Handling session timeout in ajax calls jquery jquery

Handling session timeout in ajax calls


You could write a custom [Authorize] attribute which would return JSON instead of throwing a 401 exception in case of unauthorized access which would allow client scripts to handle the scenario gracefully:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]public class MyAuthorizeAttribute : AuthorizeAttribute{    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)    {        if (filterContext.HttpContext.Request.IsAjaxRequest())        {            filterContext.Result = new JsonResult            {                Data = new                 {                     // put whatever data you want which will be sent                    // to the client                    message = "sorry, but you were logged out"                 },                JsonRequestBehavior = JsonRequestBehavior.AllowGet            };        }        else        {            base.HandleUnauthorizedRequest(filterContext);        }    }}

then decorate your controller/actions with it and on the client:

$.get('@Url.Action("SomeAction")', function (result) {    if (result.message) {        alert(result.message);    } else {        // do whatever you were doing before with the results    }});


I wouldn't change JsonRequestBehavior to AllowGet. Instead I suggest:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]public sealed class MyAuthorizeAttribute : AuthorizeAttribute{    public override void OnAuthorization(AuthorizationContext filterContext)    {        base.OnAuthorization(filterContext);        OnAuthorizationHelp(filterContext);    }    internal void OnAuthorizationHelp(AuthorizationContext filterContext)    {        if (filterContext.Result is HttpUnauthorizedResult)        {            if (filterContext.HttpContext.Request.IsAjaxRequest())            {                filterContext.HttpContext.Response.StatusCode = 401;                filterContext.HttpContext.Response.End();            }        }    }}

and add global js ajax errors handler:

   $(document).ajaxError(function (xhr, props) {        if (props.status === 401) {            location.reload();         }   }


Even though this is well past answered, I think this is the shortest and sweetest answer if you are using .NET 4.5. Little property called SuppressFormsAuthenticationRedirect which was added. Set to true and it will not perform the 302 Redirect to login page.

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.suppressformsauthenticationredirect.aspx

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]public class AjaxAuthorizeAttribute : AuthorizeAttribute{    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)    {        // returns a 401 already        base.HandleUnauthorizedRequest(filterContext);        if (filterContext.HttpContext.Request.IsAjaxRequest())        {            // we simply have to tell mvc not to redirect to login page            filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;        }    }}

Assuming you plan on handling the ajax requests fail/error callback, in which you will get a 401 Unauthorized.