Код: Выделить всё
[HttpGet]
public IActionResult KeepSessionAlive()
{
var keepAliveValue = HttpContext.Session.GetString("KeepAlive");
_logger.LogInformation($"Previous KeepAlive: {keepAliveValue}");
HttpContext.Session.SetString("KeepAlive", DateTime.UtcNow.ToString());
_logger.LogInformation($"Updated KeepAlive: {DateTime.UtcNow}");
// Generate a new anti-forgery token
var tokens = HttpContext.RequestServices
.GetRequiredService()
.GetAndStoreTokens(HttpContext);
return Json(new
{
success = true,
antiForgeryToken = tokens.RequestToken
});
}
< /code>
На стороне клиента я динамически обновляю токен анти-форугии и периодически называю эту конечную точку: < /p>
document.addEventListener("DOMContentLoaded", function () {
console.log('Document is loaded');
function keepSessionAlive() {
fetch('/Home/KeepSessionAlive', {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok');
})
.then(data => {
console.log('Session refreshed');
if (data.antiForgeryToken) {
// Update the anti-forgery token in the form or headers
document.querySelector('input[name="__RequestVerificationToken"]').value = data.antiForgeryToken;
}
})
.catch(error => {
console.log('Failed to keep session alive:', error);
})
.finally(() => {
// Schedule the next execution after 5 minutes
setTimeout(keepSessionAlive, 5 * 60 * 1000);
});
}
// Start the session-keeping mechanism
keepSessionAlive();
});
< /code>
Запрос публикации для сохранения данных: после часа времени простоя, мои запросы на пост не выполняются, и метод контроллера SaveProjectDetails не достигнут: < /p>
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult SaveProjectDetails(ProjectDetails projectDetails)
{
if (!ModelState.IsValid)
{
return BadRequest("Invalid model state");
}
_logger.LogInformation("Anti-Forgery Token Validated Successfully");
// Save logic here
return Ok(new { success = true });
}
< /code>
Вот как мои настройки сеанса и файлов cookie настроены в программе .cs: < /p>
builder.Services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(720); // Cookie expiration time
options.SlidingExpiration = true; // Reset expiration on user activity
});
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(720); // Set session timeout
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // Use HTTPS
options.Cookie.IsEssential = true;
options.Cookie.MaxAge = TimeSpan.FromMinutes(720); // Persist the cookie
});
builder.Services.AddAntiforgery(options =>
{
options.Cookie.Name = ".AspNetCore.Antiforgery";
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.MaxAge = TimeSpan.FromMinutes(720); // Persist the cookie
});
< /code>
Почему действие SaveProjectDetails не достижимо через час, несмотря на обновление сеанса с помощью KeepSessionAlive? ]
Подробнее здесь: https://stackoverflow.com/questions/793 ... psessional