简体   繁体   中英

Log out and redirect user to login screen ASP NET MVC / C #

I'm looking for a way to end my session and redirect the user to the login screen when my system gives TimeOut.

I tried to use Session.Abandon () according to some examples that I researched. But I do not know what I'm doing wrong. below is my code to do in Global.asax:

protected void Application_EndRequest(object sender, EventArgs e)
    {
        var context = new HttpContextWrapper(Context);

        if (context.Response.StatusCode == 302 && context.Request.IsAjaxRequest())
        {
            var redirectLocation = context.Response.RedirectLocation.ToString();

            context.Response.RedirectLocation = null;
            context.Response.ContentType = "text/plain";
            context.Response.Write("session_timeout;" + redirectLocation);
            Session.Abandon();
            Response.Redirect("~/Account/Login");

        }
    }

The code runs only until: context.Session.Abandon (); and does not redirect to the login screen unless I refresh the page.

public ActionResult LogOff()
    {
        HttpContext.Session.Remove(SessionKeys.UserType);//This will remove all keys from session variable. For example, if your session contains id, name, phone number, email etc.
        HttpContext.Session.RemoveAll();//This will remove all session from application
        FormsAuthentication.SignOut();            
        return RedirectToAction("Login", "Account");
    }

I was able to resolve my question this way:

1 - I set a timeout time in my Web.config by adding this tag:

<sessionState timeout="16"></sessionState>

2 - I created a function in javascript that veridifca if the timeout time came to an end:

    var sessionTimeoutWarning = @Session.Timeout- 1;

    var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;

    setTimeout('SessionEnd()', sTimeout);

    function SessionEnd() {
        alert("Your session has expired");
        window.location = "/Account/SessionTimeOutLogOff";
    }

Note: This function was put in my _Layout.chshtml

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