You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core项目服务器闲置5分钟跳转登录问题求助

问题描述

我用ASP.NET Core搭建了项目,通过HttpContext.SignInAsync()实现用户登录。本地环境里Cookie过期时间设置完全正常,但部署到服务器后,只要5分钟没操作就会自动跳回登录页。联系主机服务商后得知,是IIS应用闲置5分钟就会进入休眠状态,导致用户被强制退出登录。现在需要解决:要么延长服务器休眠时长,要么通过持续发请求避免休眠。

相关代码

登录服务代码

claims.Add(new Claim(ClaimTypes.NameIdentifier, result.Id.ToString()));

var claimsIdentity = new ClaimsIdentity(
    claims, CookieAuthenticationDefaults.AuthenticationScheme);

var authProperties = new AuthenticationProperties
{
    IsPersistent = /*dto.RememberMe*/ true,
};

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    authProperties);

return role;
}

Startup.cs 配置代码

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(opt => {
    opt.Cookie.Name = "";
    opt.ExpireTimeSpan = TimeSpan.FromSeconds(99999);
        opt.Cookie.IsEssential = true;
        opt.ReturnUrlParameter = "/Account/SignIn";
        opt.LogoutPath = "/Account/SignIn";
        opt.LoginPath = "/Account/SignIn";
        opt.AccessDeniedPath= "/Account/SignIn";
    });
解决方法

一、延长IIS应用休眠时长

如果有权限操作IIS:

  • 打开IIS管理器,找到你的应用对应的应用池
  • 右键选「高级设置」,在「进程模型」里找到「闲置超时(分钟)」,把默认5分钟改成你需要的时长(比如30、60分钟)
  • 顺便检查「回收」板块的「固定时间间隔(分钟)」,避免应用被定时回收导致用户退出

如果是虚拟主机没权限改配置,直接找服务商调整应用池的闲置超时时间就行。

二、前端发心跳请求保活

没法改服务器配置的话,就在前端定时发请求维持应用活跃:

  1. 前端加一段JS代码,每隔4分钟(比5分钟短)发个简单的GET请求到后端空接口
  2. 后端建一个不需要权限的接口,比如/api/keep-alive,只返回200状态码就行

示例前端代码:

// 每隔4分钟发一次心跳
setInterval(() => {
    fetch('/api/keep-alive', { method: 'GET' })
        .then(res => {
            if (!res.ok) console.log('心跳请求失败');
        })
        .catch(err => console.error(err));
}, 4 * 60 * 1000); // 4分钟的毫秒数

示例后端接口:

[ApiController]
[Route("api/[controller]")]
public class KeepAliveController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok();
    }
}

三、Cookie配置补充检查

虽然问题根源是IIS休眠,但可以确认下Cookie配置:

  • 你代码里IsPersistent = true,配合ExpireTimeSpan设置的时长,只要IIS不休眠,Cookie有效期就能正常生效
  • 确保没额外设置opt.Cookie.Expiration,这个属性会覆盖ExpireTimeSpan,目前你的代码没问题

内容的提问来源于stack exchange,提问作者Kocagozz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 23:10:25