ASP.Net/Session Cookie/Cookie

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Adding cache dependencies (VB.net)

<%@ Page Language="vb" %>
<%@ OutputCache Duration="300" VaryByParam="None" %>
<html>
   <head>
      <title>Adding cache dependencies in ASP.NET</title>
      <script runat="server">
         Sub Page_Load()
            Dim myArrayList As New ArrayList
            myArrayList.Add("Key1")
            myArrayList.Add("Key2")
            Response.AddCacheItemDependencies(myArrayList)
            Message.Text = DateTime.Now()
         End Sub
         Sub Button1_Click(sender As Object, e As EventArgs)
            Cache("Key1") = "value for key1"
         End Sub
         Sub Button2_Click(sender As Object, e As EventArgs)
            Cache("Key2") = "value for key2"
         End Sub
      </script>
   </head>
<body>
   <form runat="server">
      <asp:label id="Message" runat="server"/>
      <asp:button id="Button1" text="Change Key 1" onClick="Button1_Click" runat="server"/>
      <asp:button id="Button2" text="Change Key 2" onClick="Button2_Click" runat="server"/>
   </form>
</body>
</html>



Create and retrieve Cookie data (C#)

<%@ Page language="c#" src="CookieExample.aspx.cs" AutoEventWireup="false" Inherits="YourNamespace.CookieExample" %>
<HTML>
  <body>
    <form id="Form1" method="post" runat="server">
      <asp:Label id="lblWelcome" style="Z-INDEX: 100; LEFT: 16px; POSITION: absolute; TOP: 24px"
        runat="server" Width="412px" Height="130px" BackColor="LightYellow" Font-Size="Medium"
        Font-Names="Verdana" BorderWidth="2px" BorderStyle="Groove"></asp:Label>
      <asp:Button id="Button1" style="Z-INDEX: 105; LEFT: 288px; POSITION: absolute; TOP: 264px" runat="server"
        Width="137px" Text="Submit Page"></asp:Button>
      <asp:TextBox id="txtName" style="Z-INDEX: 101; LEFT: 96px; POSITION: absolute; TOP: 200px" runat="server"
        Width="184px" Height="24px"></asp:TextBox>
      <asp:Button id="cmdStore" style="Z-INDEX: 103; LEFT: 288px; POSITION: absolute; TOP: 200px"
        runat="server" Width="137px" Text="Create Cookie"></asp:Button>
      <asp:Label id="Label1" style="Z-INDEX: 104; LEFT: 24px; POSITION: absolute; TOP: 204px" runat="server"
        Width="56px" Height="16px" Font-Size="X-Small" Font-Names="Verdana">Name:</asp:Label>
    </form>
  </body>
</HTML>
<%--
using System;
using System.Collections;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Net;
namespace YourNamespace
{
  /// <summary>
  /// Summary description for CookieExample.
  /// </summary>
  public class CookieExample : System.Web.UI.Page
  {
    protected System.Web.UI.WebControls.Label lblWelcome;
    protected System.Web.UI.WebControls.TextBox txtName;
    protected System.Web.UI.WebControls.Button cmdStore;
    protected System.Web.UI.WebControls.Button Button1;
    protected System.Web.UI.WebControls.Label Label1;
  
    private void Page_Load(object sender, System.EventArgs e)
    {
      HttpCookie cookie = Request.Cookies["Preferences"];
      if (cookie == null)
      {
        lblWelcome.Text = "<b>Unknown Customer</b>";
      }
      else
      {
        lblWelcome.Text = "<b>Cookie Found.</b><br><br>";
        lblWelcome.Text += "Welcome, " + cookie["Name"];
      }
    }
    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
      //
      // CODEGEN: This call is required by the ASP.NET Web Form Designer.
      //
      InitializeComponent();
      base.OnInit(e);
    }
    
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {    
      this.cmdStore.Click += new System.EventHandler(this.cmdStore_Click);
      this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion
    private void cmdStore_Click(object sender, System.EventArgs e)
    {
      HttpCookie cookie = Request.Cookies["Preferences"];
      if (cookie == null)
      {
        cookie = new HttpCookie("Preferences");
      }
      cookie["Name"] = txtName.Text;
      cookie.Expires = DateTime.Now.AddYears(1);
      Response.Cookies.Add(cookie);
      lblWelcome.Text = "<b>Cookie Created.</b>";
      lblWelcome.Text += "New Customer: " + cookie["Name"];
    }
  }
}
--%>



Delete All Cookies (C#)

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    
    void Page_Load()
    {
        string[] cookies = Request.Cookies.AllKeys;
        foreach (string cookie in cookies)
        {
            BulletedList1.Items.Add("Deleting " + cookie);
            Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
        }
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Delete All Cookies</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <h1>Delete All Cookies</h1>
    
    <asp:BulletedList
        id="BulletedList1"
        EnableViewState="false"
        Runat="server" />
    
    </div>
    </form>
</body>
</html>



Delete Cookie (C#)

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        Response.Cookies[txtCookieName.Text].Expires = DateTime.Now.AddDays(-1);
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Delete Cookie</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:Label
        id="lblCookieName"
        Text="Cookie Name:"
        AssociatedControlID="txtCookieName"
        Runat="server" />
    <asp:TextBox
        id="txtCookieName"
        Runat="server" />
    <asp:Button
        id="btnDelete"
        Text="Delete Cookie"
        OnClick="btnDelete_Click" 
        Runat="server" />
        
    </div>
    </form>
</body>
</html>



Display all Cookie (C#)

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void Page_Load()
    {
        ArrayList colCookies = new ArrayList();
        for (int i = 0; i < Request.Cookies.Count; i++)
            colCookies.Add(Request.Cookies[i]);
        grdCookies.DataSource = colCookies;
        grdCookies.DataBind();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Get All Cookies</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:GridView
        id="grdCookies"
        Runat="server"/>
        
    </div>
    </form>
</body>
</html>



Getting cookie values in ASP.NET

<%@ Page Language="vb" %>
<html>
   <head>
      <title>Getting cookie values in ASP.NET</title>
   </head>
<body>
<p>
<%
Dim Counter1, Counter2 As Integer
Dim Keys(), SubKeys() As String
Dim CookieColl As HttpCookieCollection 
Dim Cookie As HttpCookie
Dim Expires As DateTime
CookieColl = Request.Cookies
Keys = CookieColl.AllKeys
For Counter1 = 0 To Keys.GetUpperBound(0)
   Cookie = CookieColl(Keys(Counter1))
   Response.Write("Cookie: " & Cookie.Name & "<br>")
   Expires = Cookie.Expires
   Response.Write("Expires: " & Expires & "<br>")
   SubKeys = Cookie.Values.AllKeys
   For Counter2 = 0 To SubKeys.GetUpperBound(0)
      Response.Write("Key " & CStr(Counter2) + ": " & SubKeys(Counter2) & "<br>")
      Response.Write("Value " & CStr(Counter2) + ": " & Cookie.Values(Counter2) & "<br>")
   Next Counter2
Next Counter1
%>
</p>
</body>
</html>



Save and retrieve values in Cookie (C#)

<%@ Page Language="c#" %>
<script Language="c#" runat="server">
  void Page_Load(object source, EventArgs e)
  {
    if (!(IsPostBack))
    {
      MyButton.Text = "Save Cookie";
      MyDropDownList.Items.Add("Blue");
      MyDropDownList.Items.Add("Red");
      MyDropDownList.Items.Add("Gray");
    }
  }
  public void Click(object sender, EventArgs e)
  {
    HttpCookie MyCookie = new HttpCookie("Background");
    MyCookie.Value = MyDropDownList.SelectedItem.Text;
    Response.Cookies.Add(MyCookie);
  }
</script>
<html>
  <body>
    <form id="CookieForm" method="post" runat="server">
      <asp:DropDownList id=MyDropDownList runat="server"/>
      <asp:button id=MyButton runat="server" OnClick="Click"/>
    </form>
  </body>
</html>

///////////////////////////////////////////////////

<%@ Page Language="c#" %>
  <script Language="c#" runat="server">
    void Page_Load(object source, EventArgs e)
    {
      Response.Cache.SetExpires(DateTime.Now);
    }
    string GetBackground()
    {
      return Request.Cookies["Background"].Value;
    }
  </script>
  <html>
    <body bgcolor="<% Response.Write(GetBackground()); %>">
    <asp:label id="message" runat="server" />
    </body>
  </html>



Save Cookie (Vb.net)

<%@ Page Language="VB" %>
  <script language="vb" runat="server">
      Sub Page_Load(Source As Object, E as EventArgs)
        If Not IsPostBack Then
          MyButton.Text = "Save Cookie"
          MyDropDownList.Items.Add("Blue")
          MyDropDownList.Items.Add("Red")
          MyDropDownList.Items.Add("Gray")
        End If
      End Sub
    Public Sub Click(ByVal sender As Object, ByVal e As System.EventArgs)
      Dim MyCookie As New HttpCookie("Background")
      MyCookie.Value = MyDropDownList.SelectedItem.Text
      Response.Cookies.Add(MyCookie)   
      End Sub
  </script>
<html>
  <body>
    <form id="CookieForm" method="post" runat="server">
      <asp:DropDownList id=MyDropDownList runat="server"/>
      <asp:button id=MyButton runat="server" OnClick="Click"/>
    </form>
  </body>
</html>

//////////////////////////////////////////////////////////
// Get saved Cookies 
<%@ Page Language="VB" %>
  <script language="vb" runat="server">
    Sub Page_Load(Source As Object, E as EventArgs)
      Response.Cache.SetExpires(DateTime.Now)
    End Sub
  </script>
  <html>
    <body bgcolor="<%=Request.Cookies("Background").Value%>">
    </body>
  </html>



Set cookie expire date (VB.net)

       
<%@ Page Language="VB" %>
  <script language="vb" runat="server">
      Sub Page_Load(Source As Object, E as EventArgs)
        If Not IsPostBack Then
          MyButton.Text = "Save Cookie"
          MyDropDownList.Items.Add("Blue")
          MyDropDownList.Items.Add("Red")
          MyDropDownList.Items.Add("Gray")
        End If
      End Sub
    Public Sub Click(ByVal sender As Object, ByVal e As System.EventArgs)
      Dim MyCookie As New HttpCookie("Background")
      MyCookie.Value = MyDropDownList.SelectedItem.Text
      Response.Cookies.Add(MyCookie)   
      End Sub
  </script>
<html>
  <body>
    <form id="CookieForm" method="post" runat="server">
      <asp:DropDownList id=MyDropDownList runat="server"/>
      <asp:button id=MyButton runat="server" OnClick="Click"/>
    </form>
  </body>
</html>

//////////////////////////////////////////////////////////       
       
<%@ Page Language="VB" %>
  <script language="vb" runat="server">
    Sub Page_Load(Source As Object, E as EventArgs)
      Response.Cache.SetExpires(DateTime.Now)
    End Sub
  </script>
  <html>
    <body bgcolor="<%=Request.Cookies("Background").Value%>">
    </body>
  </html>



Setting a Cookie (VB.net)

<%@ Page Language="vb" %>
<html>
   <head>
      <title>Setting a Cookie in ASP.NET</title>
      <script runat="server">
         Sub Page_Load()
            Dim myCookie As New HttpCookie("LoggedIn")
            myCookie.Value = "True"
            myCookie.Expires = DateTime.Now.AddMinutes(30)
            Response.Cookies.Add(myCookie)
         End Sub
      </script>
   </head>
<body>
   <asp:label id="Message" runat="server"/>
</body>
</html>



Setting expire date and path for cookies in ASP.NET (VHB.net)

<%@ Page Language="vb" %>
<html>
   <head>
      <title>Setting cookies in ASP.NET</title>
   </head>
<body>
<p>
<%
    Dim Cookie1 As New HttpCookie("Cookie1")
    Dim Cookie2 As New HttpCookie("Cookie2")
    Dim ExpiryDate As DateTime = DateTime.Now()
    ExpiryDate = ExpiryDate.AddHours(1)
    
    Cookie1.Value = "Cookie from nfex.ru"
    Cookie1.Expires = ExpiryDate
    Cookie1.Path = "/"
    
    Cookie2.Values("V1") = "1"
    Cookie2.Values("V2") = "2"
    Cookie2.Values("V3") = "3"
    Cookie2.Expires = ExpiryDate
    Cookie2.Path = "/"
    
    Response.Cookies.Add(Cookie1)
    Response.Cookies.Add(Cookie2)
    Response.Write("Cookies written")
%>
</p>
</body>
</html>



Write Cookie and read Cookie (VB.net)

<%@ Page Language=VB Debug=true %>
<script runat=server>
Sub SubmitBtnWrite_Click(Sender As Object, E As EventArgs)
        Response.Cookies("TestCookie1").Expires = "5/1/2010"
        Response.Cookies("TestCookie1").Value = _
            "The cookie stuff."
        Response.Cookies("TestCookie2").Expires = "5/1/2010"
        Response.Cookies("TestCookie2").Value = _
            "More cookie stuff."
End Sub
Sub SubmitBtnRead_Click(Sender As Object, E As EventArgs)
    Dim I as integer
    For I = 0 to Request.Cookies.Count - 1
        lblMessage1.Text = lblMessage1.Text  _
            & Request.Cookies.Item(I).Name & ": " _
            & Request.Cookies.Item(I).Value & "<BR>"
    Next
End Sub
</SCRIPT>
<HTML>
<HEAD>
<TITLE>Cookies Sample Page</TITLE>
</HEAD>
<BODY >
<form runat="server">
<Font Face="Tahoma">
<asp:Label
    id="lblMessage1"
    runat="Server"
    Font-Bold="True"
/>
<BR><BR>
<asp:button 
    id="butOK1"
    runat="server"
    text="Write Cookies to Browser"
    Type="Submit"
    OnClick="SubmitBtnWrite_Click" 
/>
<asp:button 
    id="butOK2"
    runat="server"
    text="Read Cookies from Browser"
    Type="Submit"
    OnClick="SubmitBtnRead_Click"
/>
</Font>
</Form>
</BODY>
</HTML>