c# - 在给定时间之前 session 超时

标签 c# asp.net asp.net-mvc forms authentication

我在 Asp.Net MVC 应用程序中使用表单例份验证,如下所示:

代码

public void SignIn(string userName, bool isCookiePersistent)
        {

            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddDays(14),
                createPersistentCookie, string.Empty);

            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, isCookiePersistent);
            if (authTicket.IsPersistent)
            {
                authCookie.Expires = authTicket.Expiration;
            }

            authCookie.Value = FormsAuthentication.Encrypt(authTicket);
            HttpContext.Current.Response.Cookies.Add(authCookie);
        }

public void SignOut()
        {
            FormsAuthentication.SignOut();
        }

问题: 问题是,如果我将表单例份验证超时设置为 4 小时,我的用户仍然会在登录后半小时后重定向到登录页面。

我已经尝试在 web.config 中同时包含 SessionSate 或执行 SessionState,但注意到正在发生。问题仍然存在。这是我下面的 web.cofig 代码。

Web.config(没有 sessionState 元素)

  <authentication mode="Forms">
      <forms loginUrl="~/LogOn/LogOn" requireSSL="false" timeout="240" defaultUrl="~/Home/Home" name="__appcookie" path="/" slidingExpiration="true" ticketCompatibilityMode="Framework40" protection="All">
      </forms>
    </authentication>

Web.config(带有 sessionState 元素)

<sessionState timeout="240"></sessionState>
 <authentication mode="Forms">
          <forms loginUrl="~/LogOn/LogOn" requireSSL="false" timeout="240" defaultUrl="~/Home/Home" name="__appcookie" path="/" slidingExpiration="true" ticketCompatibilityMode="Framework40" protection="All">
          </forms>
        </authentication>

任何人都可以让我知道在 web.config 中包含 sessionStatesessionTimeout 真的很重要吗?我不能在整个应用程序中只使用 formAuthentication 吗?

无论我是否使用sessionState,即使只使用form authentication,我的用户在登录应用程序后半小时后重定向到登录页面。 (但是我已经将 240 分钟设置为 form authentication timeout)。

谁能给我一些想法或解决方案。

提前致谢!

最佳答案

表单 ticketCompatibilityMode="Framework40" 指定票证到期日期存储为 UTC。默认值为 Framework20,它指定将票证到期日期存储为本地时间。如果您像使用 DateTime.Now 一样手动设置 FormsAuthenticationTicket 到期日期,而您的 ticketCompatibilityMode 是 Framework40,则本地和 UTC 之间会断开连接(DateTime.Now 对比 DateTime.UtcNow)。

最近我遇到了一个问题。参见 this MSDN article for more information .

关于c# - 在给定时间之前 session 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13459070/

相关文章:

c# - 将 IP 地址拆分为四个独立的值

C# - 将 xyz 平铺转换为纬度/经度,反之亦然,给出不同的结果

asp.net - 根据需要在服务器中生成并提供文件。在不消耗太多资源的情况下最好的方法是什么?

c# - 创建另一种类型的 htmlhelper 实例

c# - 如何使用 SignalR Serverless 处理用户关闭浏览器?

javascript - 对 Controller 上方法的 Ajax 调用不起作用

asp.net - GCloud - 将 App Engine Flex 连接到其他项目中的 Cloud SQL

jquery - 修复了具有排序功能的标题 GridView

c# - 在删除项目后添加成功消息,在 MVC4 中

c# - 没有 System.Web 依赖的 HttpUtility.ParseQueryString 的替代方案?