【问题标题】:session variable in c#C#中的会话变量
【发布时间】:2012-03-31 08:24:17
【问题描述】:
<configuration>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
  <sessionState timeout="1" mode="InProc" cookieless="false" >
  </sessionState>
  <compilation debug="true" targetFramework="4.0"/>
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login.aspx" timeout="1"/>
</authentication>

如果用户像这样通过身份验证,我创建了一个会话

if (HttpContext.Current.User.Identity.IsAuthenticated)
    {

        string name = HttpContext.Current.User.Identity.Name.ToString();
        Session["username"] = name;
    }

然后我正在检查会话是否仍然像这样退出

  if (Session["username"] == null)
            Response.Redirect("SessionExpired.aspx");
        else
            Response.Write("session still exist");

**问题:**会话在 1 分钟后没有变为空,用户总是登录任何帮助

这是代码:

     Welcome to ASP.NET! test1
     <p>
     To  visit  test2 go to<asp:LinkButton ID="LinkButton1" runat="server" 
      onclick="LinkButton1_Click">here</asp:LinkButton> 
     </p>
     <asp:Label ID="msg" runat="server" Text=""></asp:Label>

在服务器端

    protected void LinkButton1_Click(object sender, EventArgs e)
   {
     if (HttpContext.Current.User.Identity.IsAuthenticated)
    {

    string name = HttpContext.Current.User.Identity.Name.ToString();
    Session["username"] = name;
    if (Session["username"] == null)
        Response.Redirect("~/SessionExpired.aspx");
    else

 msg.Text = "session still exist the session will be timedout after "+Session.Timeout+ "min";
 }
 else
    Response.Write("please login");
 }

【问题讨论】:

    标签: asp.net c#-4.0


    【解决方案1】:

    【讨论】:

    • 是的。在我发布的链接中,用户也将模式更改为“inproc”
    • 这是对的,在这里他并不是说他在将其更改为 InProc 后可以正常工作。他在使用它时遇到了问题..
    • 除了默认情况下在 asp.net 中实现的成员数据库之外,我没有使用任何 sql 服务器
    • 会话应在 1 分钟不活动后超时。您是否在进行任何回发或任何活动?
    【解决方案2】:

    没有机会将 Session["username"] 对象设为 null。所以 if 语句没用..

    string name = HttpContext.Current.User.Identity.Name.ToString();
        Session["username"] = name;
        if (Session["username"] == null)
            Response.Redirect("~/SessionExpired.aspx");
    

    【讨论】:

    • 如何检查会话是否过期? if (Session["username"] == null) 是否意味着会话变量已过期:o ?
    • 您可以在为会话赋值之前检查会话是否过期。不是之后。我的意思是 if 语句应该高于 Session["username"] = name;行。
    【解决方案3】:

    @bassem ala:虽然您在配置文件中默认设置会话超时期限,但 asp.net 会检查服务器会话超时值。您必须在一分钟后手动将会话值设置为空。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 2018-02-14
      • 2012-05-22
      • 2013-02-07
      • 2011-11-09
      • 2018-02-01
      相关资源
      最近更新 更多