Redirect to login page after session is timeout

6.2k views Asked by At

First of all I have already look at the similar solution to the following ones:

ASP.NET MVC : Handle Session Expire Using Custom Attribute

Redirect to specific page after session expires (MVC4)

But I need a smart solution regarding to this problem by just typing a code on Global.asax etc. and not requiring an extra implementation on every Cntroller. Is it possible? If not, what is the best approach for redirecting to login page after session is timeout in ASP.NET MVC?

4

There are 4 answers

2
Saad Suri On

Use GlobalFilters in global.asax

GlobalFilters.Filters.Add(new SessionExpireFilterAttribute());

Reference taken from best answer's comment by Dean Ward Redirect to specific page after session expires (MVC4)

5
ivamax9 On

You can handle session timeouts in Global.asax from Session_End method. Just FYI, It has some cons: it will be called not necessarily right after the timeout and it works if your session is in runtime memory. Try it, maybe it will be enough for your case.

Another way to do it can be using SessionStateModule or creation custom HTTP module paired with some of global events which can be used for session control.

3
user1429080 On

Tested this with a freshly setup MVC application. The idea behind it, which is to inspect the state of the session for each incoming request seems to work correctly in my case.

void Application_PostAcquireRequestState(object sender, EventArgs e)
{
    HttpContext context = ((HttpApplication)sender).Context;
    if (context.Session != null)
    {
        if (context.Session["sessionExist"] is bool && (bool)context.Session["sessionExist"])
            return;
    }

    // put code here that you want to execute if the session has expired
    // for example:

    FormsAuthentication.SignOut();

    // or maybe

    context.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
}

Then add Session["sessionExist"] = true; after a user is successfully logged in.

1
rootturk On

I often see such solutions your example : http://www.c-sharpcorner.com/UploadFile/91c28d/handle-session-expire-using-custom-attribute-in-Asp-Net-mvc/

Before you can Create BaseController.cs Controller and define OnActionExecuting Method.

public class BaseController : Controller
{

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        base.OnActionExecuting(filterContext);


        if (Session["UserLogin"] == null)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "ManageAccount" }, { "action", "Login" } });
        }
    }

}

In the next step Create HomeController.cs inherited BaseController.cs file.

public class HomeController : BaseController
{
    // GET: Home
    public ActionResult Index()
    {  
        return View();
    }
}

BaseController OnActionExecuting method handled every request and check session control.

    [HttpPost]
    public ActionResult LoggedIn()
    {
        Session["UserLogin"] = true;

        return RedirectToAction("Index", "Home");
    }

Create example login post method, send request set UserLogin session parameter and redirect to Home/Index page.. Each controller that you inherit calls will perform session control for each request.

I Hope it helps.