How to get and set cookies for Windows Phone 8

How to get and set cookies for Windows Phone 8

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

To set cookies on a request message

  1. Create a System.Net.CookieContainer object for the HttpWebRequest.CookieContainer property of the HttpWebRequest.

    
    request.CookieContainer = new CookieContainer();
    
    
    
  2. Add cookie objects to the HttpWebRequest.CookieContainer by using the CookieContainer.Add method.

    
    request.CookieContainer.Add(new Uri("http://windowsteamblog.com/windows_phone/b/windowsphone/rss.aspx"),
        new Cookie("id", "1234"));
    
    
    

To get cookies on a response message

  1. Create a System.Net.CookieContainer on the request to hold cookie objects that are sent on the response. You must do this even if you are not sending any cookies.

    
    request.CookieContainer = new CookieContainer();
    
    
    
  2. Retrieve the values in the HttpWebResponse.Cookies property of HttpWebResponse. In this example, the cookies are retrieved and saved 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();
                }
            }
    
        }
    }
    
    
    

The following sample demonstrates how to create a Web request and add a cookie to the request. It also demonstrates how to extract the cookies from the Web response, write them to a file in isolated storage, and read them from isolated storage. When you run this sample, it displays the System.Net.Cookie values in a TextBlock control.


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>


  • In Visual Studio, create a new Windows Phone Application project named CookiesEx.

  • Copy and paste the code for MainPage.xaml and MainPage.xaml.cs or MainPage.xaml.vb, replacing the file contents.

Show:
© 2017 Microsoft