Hi,
I have a requirement to use global variable in MVC application, which is created using the below code. This valirable is assigned at the login time and is cleared at the time of logout. By mistake if we close the whole browser, then the variable is holding the value at the time of login. Is there any way to identify if the browser or tab is closed for making null to the variable
public static class GlobalVariable
{
static string _Id;
public static string _ID
{
get
{
return _Id;
}
set
{
_Id = value;
}
}

Aman GuptaRank #193 · 12.4K reputationPosted Sep 11, 2024, 3:44 AM EDT
Hi Anu,
In your case, since you're working with an MVC application and need to clear a global variable when the browser or tab is closed, the key is to detect when the browser or tab is being closed and then clear the value. Here's a solution using JavaScript and server-side calls to address this:
Steps:
Example:
1. JavaScript to Detect Tab Close
You can add this script in your view (e.g., Layout.cshtml):
window.addEventListener("beforeunload", function (event) { // Make an AJAX call to clear the global variable when the tab or browser is closed navigator.sendBeacon('/Account/ClearGlobalVariable'); });2. Controller Action to Clear Global Variable: Create a method in your controller to handle clearing the global variable:
public class AccountController : Controller { [HttpPost] public void ClearGlobalVariable() { // Clear the global variable when the browser or tab is closed GlobalVariable._ID = null; } }Hope this will help you Anu.
Jignesh KumarRank #91 · 22.9K reputationPosted Sep 11, 2024, 5:01 AM EDT
Hello,
you can achieve via javascript and api endpoint to clear all global variable there,
window.addEventListener('beforeunload', function() { // Send API request to the server navigator.sendBeacon('/api/clear-global-variable'); });Jignesh KumarRank #91 · 22.9K reputationPosted Sep 10, 2024, 8:08 AM EDT
Hello Anu,
You can use session management in MVC core,
While static global variables are not ideal for managing user-specific data in an ASP.NET Core MVC application, session state, offer more reliable ways to handle user-specific information and manage its lifecycle.
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(20); // Set session timeout options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); services.AddControllersWithViews(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseSession(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } }You can use in Login and Logout method as below,
public class AccountController : Controller { public IActionResult Login(string userId) { HttpContext.Session.SetString("UserId", userId); return RedirectToAction("Index", "Home"); } public IActionResult Logout() { HttpContext.Session.Remove("UserId"); return RedirectToAction("Index", "Home"); } public IActionResult SomeAction() { var userId = HttpContext.Session.GetString("UserId"); // Use userId return View(); } }Anu200 reputationPosted Sep 10, 2024, 9:08 AM EDT
Thanks Jignesh for your suggestion.
I am already using session in the project, but for some specific requirement I have to use the global variable with the session. Can you suggest a way to clear global variable on browser window close