ASP.NET Tutorial/Cookie/HttpCookie

Материал из .Net Framework эксперт
Версия от 14:57, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

HttpCookie

   <source lang="csharp">

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Untitled Page</title>

</head> <body>

   <form id="form1" runat="server">
     <asp:Label ID="myLabel" runat="server" />
   </form>

</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page {

   protected void Page_Load(object sender, EventArgs e)
   {
       HttpCookie userCookie;
       userCookie = Request.Cookies["UserID"];
       if (userCookie == null)
       {
           myLabel.Text = "Creating a cookie now.";
           userCookie = new HttpCookie("UserID", "JoeBlack");
           userCookie.Expires = DateTime.Now.AddMonths(1);
           Response.Cookies.Add(userCookie);
       }
       else
       {
           myLabel.Text = "Welcome back, " + userCookie.Value;
       }
   }

}</source>


HttpCookie (VB)

   <source lang="csharp">

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Untitled Page</title>

</head> <body>

   <form id="form1" runat="server">
     <asp:Label ID="myLabel" runat="server" />
   </form>

</body> </html> File: Default.aspx.vb

Partial Class _Default

   Inherits System.Web.UI.Page
   Protected Sub Page_Load(ByVal sender As Object, _
   ByVal e As System.EventArgs) Handles Me.Load
       Dim userCookie As HttpCookie
       userCookie = Request.Cookies("UserID")
       If userCookie Is Nothing Then
           myLabel.Text = "Cookie doesn"t exist! Creating a cookie now."
           userCookie = New HttpCookie("UserID", "JoeBlack")
           userCookie.Expires = DateTime.Now.AddMonths(1)
           Response.Cookies.Add(userCookie)
       Else
           myLabel.Text = "Welcome back, " & userCookie.Value
       End If
   End Sub

End Class</source>