Innocent Criminal
Innocent Criminal

Reputation: 196

How to redirect after session timeout in MVC .Net?

I want to redirect my page after 2 minutes of inactivity, for this I am using the below code to ping the controller every 2.5 minutes and if the session has expired I redirect to the original login page:

`<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
    var ReqTime [email protected]
        ReqTime = ReqTime * 60 * 1000 + (.5 * 60 * 1000);
    $(function () {
    setInterval(CheckSession, ReqTime);
});

function CheckSession() {
    $.post('@Url.Action("SessionInfo","Home")', null, function () {
        console.log("Time");
    });
}
</script>

Controller:

 public ActionResult SessionInfo()
    {

        if (Session["LoginUserName"]==null)
        {
             return RedirectToAction("Index","Home");
        }


    }

This code does not re-direct to the Home/Index. Can you tell me where I'm going wrong?

Upvotes: 2

Views: 2998

Answers (2)

ASalameh
ASalameh

Reputation: 803

Try using Javascript instead ,since redirect from server side need a post back

You can check session by controller and return a value to figure out if session end or not

 function CheckSession() {
    $.ajax({
        type: "GET",
        url: "@Url.Action("SessionInfo", "Home")"
    }).done(function (data) {
        if (data === true) {
            window.location.href = "@Url.Action("Index", "Home")";
        }
    }).fail(function (e) {
        alert('Error');
    });
}

Controller

public JsonResult SessionInfo()
        {

            if (Session["LoginUserName"] == null)
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            return Json(false, JsonRequestBehavior.AllowGet);
        }

This code for explaining

Upvotes: 2

Ali Bahrami
Ali Bahrami

Reputation: 6073

By making those session checking ajax request you just extend life-span of the user session.

If you would like to inform browser that user session has end I recommend to implement a SignalR service to have direct communication ( push capability ) between server and the browser ( realtime ).

Implement a SignalR service, Create a session_end method in your global.asax file, in the session_end send a message to user browser that your session has end.

Just it

Upvotes: 0

Related Questions