Jonathan Jonathan - 3 months ago 37
ASP.NET (C#) Question

How to redirect to logon page when session State time out is completed in asp.net mvc

I have an ASP.NET MVC4 application where I am implementing sessionTimeout like:

<configuration>
<system.web>
<sessionState timeout="2"></sessionState>
</system.web>
</configuration>


And in authentication:

<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="1" />
</authentication>
</system.web>
</configuration>


After the session has expired (2 mins), I need to redirect to the logon page, but the redirection doesn't occur.

How can I change the code so that it will redirect?

Answer

One way is that In case of Session Expire, in every action you have to check its session and if it is null then redirect to Login page.

But this is very hectic method To over come this you need to create your own ActionFilterAttribute which will do this, you just need to add this attribute in every action method.

Here is the Class which overrides ActionFilterAttribute.

public class SessionExpireFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;

            // check if session is supported
            CurrentCustomer objCurrentCustomer = new CurrentCustomer();
            objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
            if (objCurrentCustomer == null)
            {
                // check if a new session id was generated
                filterContext.Result = new RedirectResult("~/Users/Login");
                return;
            }

            base.OnActionExecuting(filterContext);
        }
    }

Then in action just add this attribute like so:

[SessionExpire]
public ActionResult Index()
{
     return Index();
}

This will do you work.