简体   繁体   中英

Redirect to login page after session is timeout

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?

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.

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.

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM