Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 414
Jonathan Avatar asked Dec 14 '12 05:12

Jonathan


People also ask

How does ASP.NET handle session timeout?

There are two ways to set a session timeout in ASP.NET. First method: Go to web. config file and add following script where sessionstate timeout is set to 60 seconds.


1 Answers

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.

like image 156
user1006544 Avatar answered Oct 06 '22 12:10

user1006544