sunboy_sunboy
sunboy_sunboy

Reputation: 263

ASP.NET Core : changing the session value after refreshing the page?

I want to save a number, for example 1, in the session, and every time the user refreshes the page, a number will be added to the previous number and saved in the session.

public async Task<IActionResult> ForgetPassword()
{
    int counts = 1;
    HttpContext.Session.SetInt32(CountActiveCode,counts);          
    ViewData["Counts"] = HttpContext.Session.GetInt32(CountActiveCode);
    return View();  
}

Upvotes: 0

Views: 172

Answers (1)

Yiyi You
Yiyi You

Reputation: 18189

Here is a demo to check session data and update it when every time the user refreshes the page:

public async Task<IActionResult> ForgetPassword()
{
     var number=HttpContext.Session.GetInt32("number");
     if (number == null)
     {
         HttpContext.Session.SetInt32("number", 1);
     }
     else {
         int newNumber = number ?? default(int);
         HttpContext.Session.SetInt32("number", ++newNumber);
     }
    ViewData["Counts"] = HttpContext.Session.GetInt32("number");
    return View();  
}

Update:

You can try to options.IdleTimeout in startup.cs,if you want to delete thr session after 2 minutes:

public void ConfigureServices(IServiceCollection services)
        {
    
            ...

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(2);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });
           
        }

Upvotes: 1

Related Questions