Cookie会在几分钟后过期?超时无法正常工作

时间:2017-04-25 14:16:04

标签: asp.net-mvc session forms-authentication session-cookies session-timeout

我在Login Controller中有这样的代码。当用户使用正确的用户名和密码登录时,我会创建一个cookie和会话。

Models.DTO.Security.CustomPrincipalSerializeModel serializeModel = new Models.DTO.Security.CustomPrincipalSerializeModel();
serializeModel.Id = member.Id;
serializeModel.UserName = member.UserName;
serializeModel.RoleId = member.RoleId;
serializeModel.IsAdmin = member.IsAdmin;

JavaScriptSerializer serializer = new JavaScriptSerializer();
string userData = serializer.Serialize(serializeModel);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
    1,
    model.UserName,
    DateTime.Now,
    DateTime.Now.AddMinutes(60),
    false,
    userData
    );
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
{
    HttpOnly = true

};
Response.Cookies.Add(faCookie);


Session["CartItemsCount"] = 0;

Session["CartItems"] = new List<Models.DTO.CartDTO.CartVM>();

Session["DiscountPercentage"] = member.DiscountPercentage;

Session["CreditLimit"] = member.CreditLimit;

我有以下Web.config:

<system.web>
    <sessionState timeout="60"/>
    <authentication mode="Forms">
      <forms loginUrl="~/Home/Index" timeout="60" name=".ASPXAUTH" />
    </authentication>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>

我将超时设置为在60分钟内到期。一切似乎都是对的。并且本地服务器没有问题。 但是当我在服务器中发布这个项目时,系统会在5分钟不活动后将用户重定向到Home / Index(Login Page)。

我无法弄清楚原因。有什么我想念的吗?

问题可能与机器密钥有关吗?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我使用机器密钥解决了问题。

我生成一个机器密钥,然后将其添加到web.config。

for generate machine key

我的网络配置文件的最终版本

 <system.web>
        <machineKey 
validationKey="5DEBFB5B7BA6F3E1DB190A2BF28F08AEB8964618C2895BD931A735143D1A9C61DA59443F8B407F125447A663452F76AB82F18E4191911E3D563700CD4CA27138"
decryptionKey="A0048282BE5B72D6028F46820C87A360906430E9E3D8EDE09BAB79E95AF4B9A2"
validation="SHA1" decryption="AES"
/>
        <sessionState timeout="60"/>
        <authentication mode="Forms">
          <forms loginUrl="~/Home/Index" timeout="60" name=".ASPXAUTH" />
        </authentication>
        <compilation debug="true" targetFramework="4.5.2" />
        <httpRuntime targetFramework="4.5.2" />
        <httpModules>
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
        </httpModules>
      </system.web>