Automatic logoff will occur after 15 minutes of inactivity in C# programming language

After a period of 15 minutes, the following method logs out the user. However, it currently logs out the user even if they are active.

I am seeking a solution where the method will only log out the user if they have been inactive for the full 15 minutes. Otherwise, the method should not run.

public void AutoRedirect()
{
    int int_MilliSecondsTimeOut = (this.Session.Timeout * 900000);
    string str_Script = @"
    <script type='text/javascript'> 
    intervalset = window.setInterval('Redirect()'," + int_MilliSecondsTimeOut.ToString() + @");
    function Redirect()
     {
       alert('Your session has expired and you will now be redirected to the login page.\n\n');
       window.location.href='../index.aspx'; 
     }
    </script>";
    UtilityClass.RemoveCookie("login", Response);
    ClientScript.RegisterClientScriptBlock(this.GetType(), "Redirect", str_Script);
}

Answer №1

Why not try a different approach instead of using a single 15-minute timer? How about setting the interval to 1 minute and implementing a countdown counter in your event handler?

This counter can be easily reset by various events like AJAX calls, click events, etc., which can be triggered effortlessly using jQuery's .delegate or .on methods.

If there are no resets happening, once the countdown reaches 0, you can proceed with the redirect process.

var inactivityCountdown = 15;

intervalid = window.setInterval(function Redirect()
 {
   inactivityCountdown--; 
   if (inactivityCountdown<1) {
    clearInterval(intervalid);
    alert('Your session has expired, system will now redirect to the login page!\n\n');
    window.location.href='../index.aspx'; 
   }
 }, 60*1000);

This method allows for easy resetting of the inactivityCountdown counter before it expires. Just remember to clear the interval when performing the redirect.

In the example below, I have used a 10-second countdown for testing purposes instead of minutes. You can enter text into the field or click the button to reset the countdown:

You will receive a logout message followed by a prompt to log back in via a link (simulating the redirect):

var initCountdownValue = 10;
var inactivityCountdown = initCountdownValue;
$(document).ready(function() {

  $(document).delegate("#login", "click", function(e) {
    location.reload();
  });

  function Logout() {
    document.getElementById('mainpage').style.display = "none";
    document.getElementById('loggedout').style.display = "";
    // Alternatively use: window.location.href="/logout.aspx";
  }

  var intervalid = window.setInterval(function Redirect() {
    inactivityCountdown--;
    $("#counter").text(inactivityCountdown.toString());
    if (inactivityCountdown < 1) {
      clearInterval(intervalid);
      Logout();
      alert('Your session has expired, system will now redirect to the login page!');
    }
  }, 1 * 1000);

  $(document).delegate(":input", "click change keydown", function() {
    inactivityCountdown = initCountdownValue;
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainpage" style="">
  <input type="text"></input>
  <input type="button" text="test"></input>
  <div>
    Counter:
    <div id="counter"></div>
  </div>
</div>
<div id="loggedout" style="display:none">
  You are logged out. To login, click <a id="login" href="#">here</a>
</div>

In a real production environment, it is recommended to remove the alert message and simply redirect the user to a designated logout page. The alert is purely for demonstration purposes.

Answer №2

It's important to note that the window.setInterval function remains unchanged despite any assumptions made about it being overwritten. One option is to eliminate this function and allow your IIS or a similar tool to handle it through appropriate configuration.

Alternatively, you can clear the interval and then set it again, as described in detail here: How to properly stop a window.setInterval in JavaScript?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Choose a country from a modal in a React application

click here for image description I need help implementing the screenshot above. My goal is to change the default country name and flag when a user clicks on the country dropdown menu. I have been using headless UI so far, but I'm struggling to figure ...

Tips for updating iframe source without refreshing the iframe?

I am facing an issue with two frames where I need to copy the content from the first frame (myframe) to the second frame (myframe2) using JavaScript. The challenge is that when I set the "src" attribute for myframe2, it causes a reload of FrameSecond. Is ...

Modifying HTML text with JavaScript according to the content of the currently selected div

Greetings! This is my first time posting a question, and I wanted to mention that I am relatively new to javascript/jquery. I have a gallery that displays image details on hover through text, while clicking on the image triggers a javascript function that ...

The useTransition() method in React remains stuck in the isPending state when making API calls from routes in the /pages/api directory

I'm encountering an issue with the useTransition() function where it remains true and never changes back to false. I am attempting to delete a record from MongoDB and after completion, I want to refresh the React Server Component following the guideli ...

Retrieving all the information stored in the tables

I'm struggling with retrieving the content of my table cells. Some cells contain a hyphen (-) and if they do, I want to center the text. I'm facing difficulties with my jQuery code, particularly the if statement which always evaluates to false. ...

Remove and modify an li element that has been dynamically generated within a ul list

Currently, I am facing an issue in my code. I am dynamically creating li elements by taking input from an input box and then appending the data within li tags using jQuery. However, after adding the li element, I have included a delete button. The problem ...

Having trouble with shipit.js deployment: Error encountered - git checkout undefined

I have been using shipit.js to deploy my nodejs application on an Ubuntu 16.04 server successfully. However, I recently encountered the following error: ./node_modules/shipit-cli/bin/shipit production deploy start Running 'deploy:init' task... ...

Create the final APK file using Phonegap build directly from your local machine, without the need to

While I've been using Phonegap CLI to develop my android apps and everything has been working well, I encountered an issue when trying to create the final .apk file. I have all the necessary tools - SDK, JDK, Java, and environment variables configure ...

How to categorize an array of objects based on a specific property while preserving the original object attributes

I have an array of objects with a specific property that I want to group by. My objective is to create a new array where all the objects have the same properties, but with an additional property that combines all the "value" properties into an array. Here ...

Node.js - Synchronize asynchronous calls to ensure coordinated execution in code

I am trying to figure out how to make a for loop with an async function wait until all the async functions called within it are finished before allowing the code to continue. In my scenario, I have a variable "bar" that contains a JSON array with other ne ...

Access the JavaScript variable in a webview and store it in an Android variable

I have been attempting to retrieve a variable from a webview, but I am only able to make modifications like this: browser.loadUrl("javascript:var x = document.getElementById('login').value = 'something';"); However, I need to be able ...

Purge React Query Data By ID

Identify the Issue: I'm facing a challenge with invalidating my GET query to fetch a single user. I have two query keys in my request, fetch-user and id. This poses an issue when updating the user's information using a PATCH request, as the cach ...

What is the best way to convert the data stored in an object to an array?

I have a function that is constantly checking for temperature data: {"a":"43", "b":"43", "c":"42", "d":"43", "e":"40", "f":"41", "g":"100", "h":"42.6"} My goal is to graph this data over time, but I'm struggling with how to structure it to fit the f ...

Check if the browser is compatible with the FREEZE and RESUME lifecycle events

Is there a method to determine if a browser is capable of registering the freeze and resume lifecycle events? Even after checking with Modernizr, a reliable JS library, it appears that these events are not supported. Although extremely beneficial, Safari ...

Instructions on merging elements in an array with identical property values

Consider the array below: [{a:1,b:1},{a:5,b:2},{a:10,b:2},{a:20,b:3}] Is there a way to create a new array that merges elements with the same b value, while adding up the corresponding a values? The desired output should be as follows: [{a:1,b:1},{a:(5+10 ...

Pass a photo along with additional characteristics to the post endpoint in the API

Using the code snippet below, I am able to send an image to a post method and save it as a BLOB in the database successfully: Angular Code: public postUploadedFile(file:any){ this.formData = new FormData(); this.formData.append('file',fi ...

How many intricate objects are instantiated in memory when running the code snippet provided above?

When looking at the given code, how many complex objects can we identify in memory? function Foo() { this.one = function() { return "one"; } } var f = new Foo(); Foo.two = function() { return "two"; }; Here's what I see: The Foo co ...

Angular has trouble displaying information across multiple HTML files

I have created an HTML file to display some data. The initial HTML file named disc-log.html looks like this: <div> <h2>Discs</h2> <jhi-alert></jhi-alert> <div class="container-fluid"> <div class=" ...

Utilize Object literal manipulation to include properties in a specific sequence

Working on a tool to generate Nassi-Shneiderman diagrams online, where each diagram is represented as an object literal with unlimited possible children. As I aim to add a sequence into the while loop following the first sequence, I encounter the challeng ...

Defining types for functions that retrieve values with a specified default

My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist. async get(key: string, def_value?: any): Promise<any> { const v = await redisInstance.get(key); return v ? v : def_value; } W ...