c#中的会话变量

时间:2012-03-31 08:24:17

标签: asp.net c#-4.0

<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");
 }

3 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

没有机会将Session [“username”]对象设为null。所以如果陈述无用..

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

答案 2 :(得分:0)

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