Udostępnij za pośrednictwem


Cookie Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Provides an object for use with HTTP requests to persist state information for a Silverlight-based application.

Inheritance Hierarchy

System.Object
  System.Net.Cookie

Namespace:  System.Net
Assembly:  System.Net (in System.Net.dll)

Syntax

'Declaration
Public NotInheritable Class Cookie
public sealed class Cookie

The Cookie type exposes the following members.

Constructors

  Name Description
Public methodSupported by Silverlight for Windows Phone Cookie() Initializes a new instance of the Cookie class.
Public methodSupported by Silverlight for Windows Phone Cookie(String, String) Initializes a new instance of the Cookie class with the specified name and value.
Public methodSupported by Silverlight for Windows Phone Cookie(String, String, String) Initializes a new instance of the Cookie class with the specified name, value and path.
Public methodSupported by Silverlight for Windows Phone Cookie(String, String, String, String) Initializes a new instance of the Cookie class with the specified name, value, path and domain.

Top

Properties

  Name Description
Public propertySupported by Silverlight for Windows Phone Comment Gets or sets an optional comment that provides the intended use of the cookie.
Public propertySupported by Silverlight for Windows Phone CommentUri Gets or sets a Uniform Resource Identifier (URI) comment that the server provides for this Cookie.
Public propertySupported by Silverlight for Windows Phone Discard Gets or sets a values that indicates whether the client is to discard the Cookie at the end of the current session.
Public propertySupported by Silverlight for Windows Phone Domain Gets or sets the domain of a Uniform Resource Identifier (URI) for which the cookie is valid.
Public propertySupported by Silverlight for Windows Phone Expired Gets or sets a values that indicates whether this Cookie is no longer valid.
Public propertySupported by Silverlight for Windows Phone Expires Gets or sets the expiration date and time for the Cookie.
Public propertySupported by Silverlight for Windows Phone HttpOnly Gets or sets a value that indicates whether a page script or other active content can access this cookie.
Public propertySupported by Silverlight for Windows Phone Name Gets or sets the name of this cookie.
Public propertySupported by Silverlight for Windows Phone Path Gets or sets the path portion of a Uniform Resource Identifier (URI) to which this cookie applies.
Public propertySupported by Silverlight for Windows Phone Port Gets or sets a list of Transmission Control Protocol (TCP) ports to which this cookie applies.
Public propertySupported by Silverlight for Windows Phone Secure Gets or sets a value that indicates whether including the cookie on subsequent client requests requires the request be sent with Secure Hypertext Transport Protocol (HTTPS).
Public propertySupported by Silverlight for Windows Phone TimeStamp Gets the date and time that this Cookie was created.
Public propertySupported by Silverlight for Windows Phone Value Gets or sets the value of the Cookie.
Public propertySupported by Silverlight for Windows Phone Version Gets or sets a single digit that indicates the version of HTTP state maintenance to which the cookie conforms.

Top

Methods

  Name Description
Public methodSupported by Silverlight for Windows Phone Equals Determines if two Cookie objects are equal. (Overrides Object.Equals(Object).)
Protected methodSupported by Silverlight for Windows Phone Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone GetHashCode Gets the hash code for this Cookie. (Overrides Object.GetHashCode().)
Public methodSupported by Silverlight for Windows Phone GetType Gets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows Phone MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone ToString Returns a string representation of the Cookie suitable for including in an HTTP cookie request. (Overrides Object.ToString().)

Top

Remarks

The Cookie class is used by a client application to retrieve information about cookies that are received with HTTP responses. The following cookie formats are supported during parsing of the HTTP response headers: the original Netscape specification, RFC 2109, and RFC 2965.

Cookies are stored in a CookieContainer on a Web request, and a CookieCollection on a Web response. You must always create a CookieContainer to send with a request if you want cookies to be returned on the response. This is also true for HTTPOnly cookies, which you cannot retrieve.

Examples

The following example shows how to add cookies to a request and retrieve them from a response.

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports System.Net.Browser
Imports System.IO
Imports System.Text
Imports System.IO.IsolatedStorage

Partial Public Class MainPage
    Inherits UserControl
    Public Sub New()

        InitializeComponent()
    End Sub

    Private Sub button1_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        InitializeWebRequestClientStackForURI()
        ReadFromIsolatedStorage()
    End Sub

    Private Sub InitializeWebRequestClientStackForURI()
        ' Create the client WebRequest creator. 
        Dim creator As IWebRequestCreate = WebRequestCreator.ClientHttp

        ' Register both http and https. 
        WebRequest.RegisterPrefix("http://", creator)
        WebRequest.RegisterPrefix("https://", creator)


        ' Create a HttpWebRequest. 
        Dim request As HttpWebRequest = DirectCast( _
            WebRequest.Create("http://api.search.live.net/clientaccesspolicy.xml"),  _
            HttpWebRequest)

        'Create the cookie container and add a cookie. 
        request.CookieContainer = New CookieContainer()

        ' This example shows manually adding a cookie, but you would most
        ' likely read the cookies from isolated storage.
        request.CookieContainer.Add(New Uri("http://api.search.live.net"), _
            New Cookie("id", "1234"))

        ' Send the request. 
        request.BeginGetResponse(New AsyncCallback(AddressOf ReadCallback), request)
    End Sub

    ' Get the response and write cookies to isolated storage. 
    Private Sub ReadCallback(ByVal asynchronousResult As IAsyncResult)
        Dim request As HttpWebRequest = DirectCast(asynchronousResult.AsyncState,  _
            HttpWebRequest)
        Dim response As HttpWebResponse = _
        DirectCast(request.EndGetResponse(asynchronousResult), HttpWebResponse)
        Using isf As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForSite()
            Using isfs As IsolatedStorageFileStream = isf.OpenFile("CookieExCookies", _
                FileMode.OpenOrCreate, FileAccess.Write)
                Using sw As New StreamWriter(isfs)
                    For Each cookieValue As Cookie In response.Cookies
                        sw.WriteLine("Cookie: " + cookieValue.ToString())
                    Next
                    sw.Close()
                End Using

            End Using
        End Using
    End Sub

    Private Sub ReadFromIsolatedStorage()
        Using isf As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForSite()
            Using isfs As IsolatedStorageFileStream = isf.OpenFile("CookieExCookies", _
                FileMode.Open)
                Using sr As New StreamReader(isfs)
                    tb1.Text = sr.ReadToEnd()
                    sr.Close()
                End Using

            End Using
        End Using
    End Sub

End Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Net.Browser;
using System.IO;
using System.Text;
using System.IO.IsolatedStorage;


namespace CookiesEx
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            InitializeWebRequestClientStackForURI();
            ReadFromIsolatedStorage();
        }

        private void InitializeWebRequestClientStackForURI()
        {
            // Create the client WebRequest creator.
            IWebRequestCreate creator = WebRequestCreator.ClientHttp;

            // Register both http and https.
            WebRequest.RegisterPrefix("http://", creator);
            WebRequest.RegisterPrefix("https://", creator);


            // Create a HttpWebRequest.
            HttpWebRequest request = (HttpWebRequest)
                WebRequest.Create("http://api.search.live.net/clientaccesspolicy.xml");

            //Create the cookie container and add a cookie.
            request.CookieContainer = new CookieContainer();


            // This example shows manually adding a cookie, but you would most
            // likely read the cookies from isolated storage.
            request.CookieContainer.Add(new Uri("http://api.search.live.net"),
                new Cookie("id", "1234"));

            // Send the request.
            request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
        }

        // Get the response and write cookies to isolated storage.
        private void ReadCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)
                request.EndGetResponse(asynchronousResult);
            using (IsolatedStorageFile isf =
                IsolatedStorageFile.GetUserStoreForSite())
            {
                using (IsolatedStorageFileStream isfs = isf.OpenFile("CookieExCookies",
                    FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (StreamWriter sw = new StreamWriter(isfs))
                    {
                        foreach (Cookie cookieValue in response.Cookies)
                        {
                            sw.WriteLine("Cookie: " + cookieValue.ToString());
                        }
                        sw.Close();
                    }
                }

            }
        }
        private void ReadFromIsolatedStorage()
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite())
            {
                using (IsolatedStorageFileStream isfs =
                   isf.OpenFile("CookieExCookies", FileMode.Open))
                {
                    using (StreamReader sr = new StreamReader(isfs))
                    {
                        tb1.Text = sr.ReadToEnd();
                        sr.Close();
                    }
                }

            }
        }


    }
}
<UserControl x:Class="CookiesEx.MainPage"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="https://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <StackPanel x:Name="LayoutRoot">
         <Button Width="200" Height="50" Content="Click to send request" 
                HorizontalAlignment="Left"
                x:Name="button1" Click="button1_Click" Margin="5"/>
        <TextBlock  Margin="5" Width="600" Height="400" x:Name="tb1"
                    HorizontalAlignment="Left" />
     </StackPanel>
</UserControl>

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.