title: Login and Logout in master page
body: <p>Here login and logout buttons in master page. In login page is using FormsAuthenticationTicket and HttpCookie, so in master page I want to check the forms authentication and then display logout if is authenticated and hide login. If not authenticated display login and hide logout. How can I do that?</p>
  
  <p>Login:</p>
  
  <pre><code>com.CommandText = "select [id], [username],[password], [type] FROM [users] WHERE [username] =@username AND [password]= @pass";
  com.Parameters.AddWithValue("@username", UserName.Text);
   com.Parameters.AddWithValue("@pass", Password.Text);
   //  conn.Open();
   SqlDataReader rd = com.ExecuteReader();
  
   if (rd.Read())
      {
  
      var _id = rd["id"].ToString();
  
      var _fname = rd["username"].ToString();
  
      FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
  
             1,
             _id,
             DateTime.Now,
             DateTime.Now.AddMonths(1),
             true,
              "." + _fname,
             FormsAuthentication.FormsCookiePath);
          string hashed_ticket = FormsAuthentication.Encrypt(ticket);
          HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashed_ticket);
  
          if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
  
          Response.Cookies.Add(cookie);
  
              Response.Redirect("UserProfile.aspx");
  
         }
      else
      {
          ClientScript.RegisterStartupScript(Page.GetType(), "validation", "&lt;script language='javascript'&gt;alert('Invalid Username and Password')&lt;/script&gt;");
      }
  }
  </code></pre>
  
  <p>Master page HTML:</p>
  
  <pre><code>&lt;ul class="nav navbar-nav navbar-right"&gt;
  &lt;li&gt;&lt;asp:LinkButton ID="login" runat="server"
  PostBackUrl="~/Login1.aspx"&gt;Login&lt;/asp:LinkButton&gt; &lt;/li&gt;
  &lt;li&gt; &lt;asp:LinkButton ID="Logout" runat="server" CausesValidation="False" onclick="Logout_Click" style="text-align: right"&gt;(logout)&lt;/asp:LinkButton&gt;&lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>Code behind Master Page:</p>
  
  <pre><code>if (!HttpContext.Current.User.Identity.IsAuthenticated)
      {
          Logout.Visible = false;
  
  
      }
      else
      {
          Logout.Visible = true;
          if (Request.Cookies[FormsAuthentication.FormsCookiePath] != null)
          {
          FormsIdentity user = (FormsIdentity)HttpContext.Current.User.Identity;
          FormsAuthenticationTicket ticket = user.Ticket;
          login.Text = "You are logged-in  " + ticket.UserData.Split('.')+ "!";
          }
      }
  </code></pre>