Session

Сессия — это текстовая информация, которая хранится на сервере, в отличие от cookie, которая хранится в браузере пользователя.
Использует оперативную память, которая ограничена.
Скрыть

Показать

Копировать
  Default.aspx  
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <meta charset="utf-8" />
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
  <div>
   <asp:Label ID="Label1" runat="server" Text="Name : "></asp:Label>
   &nbsp;&nbsp;
   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
   &nbsp;&nbsp;
   <asp:Button ID="Button1" runat="server" Text="OK" OnClick="Button1_Click" Width="54px" />
   &nbsp;&nbsp;
   <asp:Button ID="Button2" runat="server" Text="Delete" OnClick="Button2_Click" />
   <br />
   <br />
   <a target="_blank" href="a.aspx">go to a page of a</a>
  </div>
 </form>
</body>
</html>
Скрыть

Показать

Копировать
  Default.aspx.cs  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class _Default : System.Web.UI.Page {
 protected void Page_Load(object sender, EventArgs e) {
 
 }
 //OK
 protected void Button1_Click(object sender, EventArgs e) {
  //запись значения в сессию
  Session["name"] = TextBox1.Text;
  //по умолчанию, значение сессии в оперативной памяти компьютера сервера
  //сохраняется 20 минут, что бы увеличить или уменьшить это значение,
  //нужно воспользоваться Timeout
  Session.Timeout = 5;
 }
 //Delete
 protected void Button2_Click(object sender, EventArgs e) {
  //удаляем все значения из сессии
  Session.Clear();
  //в ответе браузеру, заставляем его сделать запрос на эту страницу
  Response.Redirect(Request.Url.PathAndQuery);
 }
}
Скрыть

Показать

Копировать
  a.aspx  
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="a.aspx.cs" Inherits="a" %>
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <meta charset="utf-8" />
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
  <div>
   <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
  </div>
 </form>
</body>
</html>
Скрыть

Показать

Копировать
  a.aspx.cs  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class a : System.Web.UI.Page {
 protected void Page_Load(object sender, EventArgs e) {
  string str = Session["name"] as string;
  if(str != null) {
   Label1.Text = "Hello " + str + " !";
  }
  else {
   Label1.Text = string.Empty;
  }
 }
}