Windows Dev Center

Cookie Class

Provides an object for use with HTTP requests to persist state information for a Windows Phone-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 methodCookie()Initializes a new instance of the Cookie class.
Public methodCookie(String, String)Initializes a new instance of the Cookie class with the specified name and value.
Public methodCookie(String, String, String)Initializes a new instance of the Cookie class with the specified name, value and path.
Public methodCookie(String, String, String, String)Initializes a new instance of the Cookie class with the specified name, value, path and domain.
Top

  NameDescription
Public propertyCommentGets or sets an optional comment that provides the intended use of the cookie.
Public propertyCommentUriGets or sets a Uniform Resource Identifier (URI) comment that the server provides for this Cookie.
Public propertyDiscardGets or sets a values that indicates whether the client is to discard the Cookie at the end of the current session.
Public propertyDomainGets or sets the domain of a Uniform Resource Identifier (URI) for which the cookie is valid.
Public propertyExpiredGets or sets a values that indicates whether this Cookie is no longer valid.
Public propertyExpiresGets or sets the expiration date and time for the Cookie.
Public propertyHttpOnlyGets or sets a value that indicates whether a page script or other active content can access this cookie.
Public propertyNameGets or sets the name of this cookie.
Public propertyPathGets or sets the path portion of a Uniform Resource Identifier (URI) to which this cookie applies.
Public propertyPortGets or sets a list of Transmission Control Protocol (TCP) ports to which this cookie applies.
Public propertySecureGets 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 propertyTimeStampGets the date and time that this Cookie was created.
Public propertyValueGets or sets the value of the Cookie.
Public propertyVersionGets or sets a single digit that indicates the version of HTTP state maintenance to which the cookie conforms.
Top

  NameDescription
Public methodEqualsDetermines if two Cookie objects are equal. (Overrides Object.Equals(Object).)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeGets the hash code for this Cookie. (Overrides Object.GetHashCode().)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns 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.

Capabilities

If you use this API in your app, you must specify the following capabilities in the app manifest. Otherwise, your app might not work correctly or it might exit unexpectedly.

ID_CAP_NETWORKING

Windows Phone 8, Windows Phone OS 7.1

For more info, see App capabilities and hardware requirements for Windows Phone 8.

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 : PhoneApplicationPage
    {

        public MainPage()
        {
            InitializeComponent();

        }

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

        private void InitializeWebRequestClientStackForURI()
        {

            // Create a HttpWebRequest.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("http://windowsteamblog.com/windows_phone/b/windowsphone/rss.aspx"));

            //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://windowsteamblog.com/windows_phone/b/windowsphone/rss.aspx"),
                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.GetUserStoreForApplication())
            {
                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.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream isfs =
                   isf.OpenFile("CookieExCookies", FileMode.OpenOrCreate))
                {
                    using (StreamReader sr = new StreamReader(isfs))
                    {
                        tb1.Text = sr.ReadToEnd();
                        sr.Close();
                    }
                }

            }
        }


    }
}



<phone:PhoneApplicationPage x:Class="CookiesEx.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="800">
    <StackPanel x:Name="LayoutRoot" Width="390">
         <Button Width="372" Height="173" Content="Click to send request" 
                HorizontalAlignment="Left"
                x:Name="button1" Click="button1_Click" Margin="5"/>
        <TextBlock TextWrapping="Wrap" Foreground="{StaticResource PhoneForegroundBrush}" Height="267" Name="tb1" Width="382" FontSize="22" />
    </StackPanel>
</phone:PhoneApplicationPage>


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

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

Show:
© 2015 Microsoft