Automatically logging users out of a website

codesnippetSession state is a funny thing.  It works really well.  But if users don’t stay active, they’ll lose their session.  That can make for some really strange problems if session isn’t used immediately.  Of course session can be checked for, but that’s a hassle.  It would be easier to simply log users out before their session expires.

This is actually a very simple thing to do.  Using the HTML tag as follows:

<meta http-equiv="refresh" content="5;URL=''">

Here, the page is going to refresh after 5 seconds and will refresh to a URL.  This is handy, but we don’t want to refresh the page if the user isn’t logged in (like if they’re on the login page).

In C#/ASP.Net/MVC, this is pretty easy.  Simply check to see if the request has been authenticated.  Furthermore, rather than redirect to a static URL, you should make use of the @Url.Content method to have the system properly redirect to your logout page.

@if (Request.IsAuthenticated)
 <meta http-equiv="refresh" content="5;URL='@Url.Content("~/Home/Logout")'" />

The logout page simply signs the user out and performs it’s own redirect to the index page.

public ActionResult Logout()
      return RedirectToAction("Index");

Thanks to Wikipedia for the quick info!

Scroll To Top