Authentication and Session Check in Ajax Call Request

1. Create action result method in controller.

In this action method check user authenticated and session.If session is null or user is not authenticated then

return json result(redirect on Logout action) otherwise return null.

  1. public ActionResult IsSessionInPro()  
  2.   
  3. {  
  4.   
  5.     if ((User.Identity.IsAuthenticated) || SessionManager.Instance.CurrentUser == null)  
  6.   
  7.     {  
  8.   
  9.         if (HttpContext.Response.StatusCode == 401)  
  10.   
  11.         {  
  12.   
  13.             HttpContext.Response.SuppressFormsAuthenticationRedirect = true;  
  14.   
  15.             HttpContext.Response.End();  
  16.   
  17.             return new JsonResult {  
  18.                 Data = new {  
  19.                     message = "logout"  
  20.                 }, JsonRequestBehavior = JsonRequestBehavior.AllowGet  
  21.             };  
  22.   
  23.         }  
  24.   
  25.     }  
  26.   
  27.     return null;  
  28.   
  29. }  

2. ajaxStart funcation excute before ajax call

  1. $(document).ajaxStart(function()  
  2. {  
  3.   
  4.     $.ajax({  
  5.   
  6.         type: 'POST',  
  7.   
  8.         url: '@Url.Action("IsSessionInPro", "ControllerName")',  
  9.   
  10.         async: false,  
  11.   
  12.         success: function(data)  
  13.       {  
  14.   
  15.             if (data == "logout")  
  16.             {  
  17.   
  18.                 window.location.href = '@Url.Action("ActionName", "ControllerName")';  
  19.   
  20.             }  
  21.   
  22.         }  
  23.   
  24.     });  
  25.   
  26. });  

3. ajaxError function call when any arror eccure in ajax call.

  1. $(document).ajaxError(function(e, xhr)  
  2. {  
  3.   
  4.     if (xhr.status == 401)  
  5.   
  6.         window.location.href = '@Url.Action("ActionName", "ControllerName")';  
  7.   
  8. });