Basic use of session in ASP.NET MVC is as follows:

  • Check user is logged in or not
  • to carry authorization data of user logged in
  • to carry temporary alternative data
  • Check session Timeout on user action for every controller

Using asynchronous (AJAX) request it's a very common state of affairs to use jquery AJAX or unobtrusive AJAX API of ASP.NET MVC 5 to create asynchronous request in MVC 5. Each jquery AJAX and unobtrusive AJAX square measure very powerful to handle asynchronous mechanism. however in most things, we like better to use jquery AJAX to possess fine tuned control over the application. And currently suppose we wish to see the session timeout for every asynchronous call in our application. we are using JSON to grab an information on form and send it with asynchronous request. Therefore we dropped in situation where:

1. Normal direct won’t work well
RedirectToAction("LoginView", "LoginController");

2. We need to ascertain session timeout in action technique. A repetitive code in every action method therefore reduced code reusability and maintainability.

if (session.IsNewSession || Session["LoginUser"] == null) { //redirection logic 

We can use base controller class or take advantage of action filters of ASP.NET MVC 5. using base controller class and preponderant OnActionExecuting methodology of Controller class:
public class MyBaseController : Controller

{

    protected override void OnActionExecuting(ActionExecutingContext filterContext)

   {

        HttpSessionStateBase session = filterContext.HttpContext.Session;
        if (session.IsNewSession || Session["LoginUser"] == null)

        {

            filterContext.Result = Json("Session Timeout", "text/html");

        }

   }

}

And inheriting Base Class:

public class MyController : BaseController

{

//your action methods…

}

Limitation of this approach is that it covers up every action method.Using action filter attribute class of ASP.NET MVC 5. Therefore we will fine tune every controller action as needed.
      [AttributeUsage(AttributeTargets.Class |

    AttributeTargets.Method, Inherited = true, AllowMultiple = true)]

     public class SessionTimeoutFilterAttribute : ActionFilterAttribute

     {
   
       public override void OnActionExecuting(ActionExecutingContext filterContext)

    {

       HttpSessionStateBase session = filterContext.HttpContext.Session;

        // If the browser session or authentication session has expired

        if (session.IsNewSession || Session["LoginUser"] == null)

        {

            if (filterContext.HttpContext.Request.IsAjaxRequest())

            {

                
JsonResult result = Json("SessionTimeout", "text/html");
                filterContext.Result = result;

            }

            else

            {

                // For round-trip requests,

               filterContext.Result = new RedirectToRouteResult(

                new RouteValueDictionary {

                { "Controller", "Accounts" },

                { "Action", "Login" }

                });

            }

        }

        base.OnActionExecuting(filterContext);

    }

}


Jquery code at client side

$.ajax({

    type: "POST",

    url: "controller/action",

    contentType: "application/json; charset=utf-8",

    dataType: "json",

    data: JSON.stringify(data),

    async: true,

    complete: function (xhr, status) {

            if (xhr.responseJSON == CONST_SESSIONTIMEOUT) {

                RedirectToLogin(true);

                return false;

            }

            if (status == 'error' || !xhr.responseText) {

                alert(xhr.statusText);

            }

       }

    });