0

I have a problem where the user is logged out all the time even though the function logout hasn't been executed. It seems like this is due to the code being in c# (this is in a razor layout page mvc4)

<script type="text/javascript">
    var idleTimer = 0;
    function notIdle() 
    {
        clearTimeout(idleTimer);     
        idleTimer = setTimeout(function () { logout() }, 5000);
    }

    function logout()           
    {
        @if (Request.IsAuthenticated )
        {
            WebSecurity.Logout();                  
        }
        window.location.reload();
        clearTimeout(idleTimer);

    }         
</script> 
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
zms6445
  • 317
  • 6
  • 22
  • 1
    Yeah, the C# code is going to run on the server side when the page is loaded. If you want to call a server-side method from javascript, you'll have to make an AJAX call or something. – Ryan M Apr 16 '13 at 19:48

1 Answers1

0

Your C# code will be run when the page is loaded, as Ryan mentioned. I can suggest to make a controller method Logout, put your code there, and in your script logout() function redirect to that method. The code would be like this:
HTML

<button onclick="logout()">Logout</button>

Javascript

    //I don't really know your logic behind those timeouts, so I leave them as is
    var idleTimer = 0;
    function notIdle() 
    {
        clearTimeout(idleTimer);     
        idleTimer = setTimeout(function () { logout() }, 5000);
    }

    function logout()           
    {
        location.href = "Home/Logout"; 
        //"Home" is the name of your controller, where you will put the Logout method.
    } 

C#

public ActionResult Logout()
{
    if (Request.IsAuthenticated)
    {
        WebSecurity.Logout();
    }
    return RedirectToAction("Index", "Home"); //redirect to your previous page
}
Artyom Neustroev
  • 8,627
  • 5
  • 33
  • 57
  • Not really what I'm looking for as this code is just to log out a user if they are idle. I realized that I could check if the aspxAuth cookie is present to check if the user is authenticated. – zms6445 Apr 16 '13 at 20:03