简体   繁体   中英

Redirect back to login page after session timeout ASP.NET 5 MVC 6

I would like to automatically redirect control to my Login page after session timeout.

So far i have added

services.AddCaching();
    services.AddSession(options => {
        options.IdleTimeout = TimeSpan.FromMinutes(20);
        options.CookieName = ".AIM";
    });

to my startup.cs file.

Anybody please let me know how to automatically be transferred to Login page after session timeout instead of clicking any button or link. I am currently using MVC6 ASP.NET5

If you are talking about "authentication session" (basically an authentication cookie), then once it (cookie) expires you will be automatically redirected to Login page next time you try to access any page that is marked with AuthorizeAttribute .

If you are talking about regular session you can write some JavaScript that will do an AJAX polling to determine whether the session is alive

Controller code:

[HttpPost]
public JsonResult IsSessionAlive()
{ 
    if (Session.Contents.Count == 0)
    {
        return this.Json(new{ IsAlive = false}, JsonRequestBehavior.AllowGet)
    }
    return this.Json(new{ IsAlive = true}, JsonRequestBehavior.AllowGet)
}

client side JavaScript

function IsSessionAlive(){
  $.post( "SomeController/IsSessionAlive", function( data ) {
    if(!data.IsAlive)
    { 
        //If you may need to logout current user first than:
        $.post( '@Url.Action("LogOut","Account")', function( data ) {
             window.location.href = '@Url.Action("Login","Account")';
        });

        //if you don't need the logout:
        window.location.href = '@Url.Action("Login","Account")';
    }
  });
}

$(function(){
     //set interval to 5 minutes
     window.setInterval(IsSessionAlive, 300000);
})

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