【问题标题】:Increase life time for Asp.net authentication cookie增加 Asp.net 身份验证 cookie 的生命周期
【发布时间】:2026-02-24 06:25:02
【问题描述】:

我使用以下代码设置身份验证 cookie:

System.Web.Security.FormsAuthentication.SetAuthCookie(Profile.Email, true);

我的问题是如何增加此身份验证 cookie 的使用寿命?

【问题讨论】:

    标签: asp.net cookies forms-authentication asp.net-authentication


    【解决方案1】:

    超时主要在 web.config 文件中设置,您可以在代码中设置,但我不建议这样做。

    这些是默认设置,您可以看到以分钟为单位指定的超时值。

    <system.web>
      <authentication mode="Forms">
        <forms loginUrl="Login.aspx"
               protection="All"
               timeout="30"
               name=".ASPXAUTH" 
               path="/"
               requireSSL="false"
               slidingExpiration="true"
               defaultUrl="default.aspx"
               cookieless="UseDeviceProfile"
               enableCrossAppRedirects="false" />
      </authentication>
    </system.web>
    

    【讨论】:

      【解决方案2】:

      这是设置时间的方法。 (例如,两周到期)。

      var cookie = FormsAuthentication.GetAuthCookie("user-name", false);
      cookie.Expires = DateTime.UtcNow.AddDays(14);
      Response.Cookies.Add(cookie);
      

      【讨论】:

      • 这是一个不错的解决方案,但最好使用Response.Cookies.Set 而不是Add 来更新cookie而不是添加另一个。