Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

Cookie Class

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

Namespace:  System.Net
Assembly:  System.Net (in System.Net.dll)
public sealed class Cookie

The Cookie type exposes the following members.

  NameDescription
Public methodSupported by Silverlight for Windows PhoneCookie()Initializes a new instance of the Cookie class.
Public methodSupported by Silverlight for Windows PhoneCookie(String, String)Initializes a new instance of the Cookie class with the specified name and value.
Public methodSupported by Silverlight for Windows PhoneCookie(String, String, String)Initializes a new instance of the Cookie class with the specified name, value and path.
Public methodSupported by Silverlight for Windows PhoneCookie(String, String, String, String)Initializes a new instance of the Cookie class with the specified name, value, path and domain.
Top
  NameDescription
Public propertySupported by Silverlight for Windows PhoneCommentGets or sets an optional comment that provides the intended use of the cookie.
Public propertySupported by Silverlight for Windows PhoneCommentUriGets or sets a Uniform Resource Identifier (URI) comment that the server provides for this Cookie.
Public propertySupported by Silverlight for Windows PhoneDiscardGets 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 PhoneDomainGets or sets the domain of a Uniform Resource Identifier (URI) for which the cookie is valid.
Public propertySupported by Silverlight for Windows PhoneExpiredGets or sets a values that indicates whether this Cookie is no longer valid.
Public propertySupported by Silverlight for Windows PhoneExpiresGets or sets the expiration date and time for the Cookie.
Public propertySupported by Silverlight for Windows PhoneHttpOnlyGets or sets a value that indicates whether a page script or other active content can access this cookie.
Public propertySupported by Silverlight for Windows PhoneNameGets or sets the name of this cookie.
Public propertySupported by Silverlight for Windows PhonePathGets or sets the path portion of a Uniform Resource Identifier (URI) to which this cookie applies.
Public propertySupported by Silverlight for Windows PhonePortGets or sets a list of Transmission Control Protocol (TCP) ports to which this cookie applies.
Public propertySupported by Silverlight for Windows PhoneSecureGets 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 PhoneTimeStampGets the date and time that this Cookie was created.
Public propertySupported by Silverlight for Windows PhoneValueGets or sets the value of the Cookie.
Public propertySupported by Silverlight for Windows PhoneVersionGets or sets a single digit that indicates the version of HTTP state maintenance to which the cookie conforms.
Top
  NameDescription
Public methodSupported by Silverlight for Windows PhoneEqualsDetermines if two Cookie objects are equal. (Overrides Object.Equals(Object).)
Protected methodSupported by Silverlight for Windows PhoneFinalizeAllows 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 PhoneGetHashCodeGets the hash code for this Cookie. (Overrides Object.GetHashCode().)
Public methodSupported by Silverlight for Windows PhoneGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneToStringReturns a string representation of the Cookie suitable for including in an HTTP cookie request. (Overrides Object.ToString().)
Top

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.

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


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="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://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>


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

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

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.