bassem ala
bassem ala

Reputation: 191

session variable in c#

<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>

i created a session if the user is authenticated like this

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

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

then i am checking if the session still exit like this

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

**the problem : **the session is not getting null after 1 min and the user is always login any help

this is the code:

     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>

in server side

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

Upvotes: 1

Views: 2510

Answers (3)

hkutluay
hkutluay

Reputation: 6944

There is no chance to be Session["username"] object to null. so if statement useless..

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

Upvotes: 1

R.D.
R.D.

Reputation: 7403

@bassem ala:though you are setting session time out period in configuration file by default asp.net checks servers session time out value.you have to manually set session values null after one minute.

Upvotes: 0

TRR
TRR

Reputation: 1643

Why isnt the session timeout working when set to SqlServer? i think this will help you.

Upvotes: 2

Related Questions