Export (0) Print
Expand All

How to: Get and Set Cookies

Silverlight

If you specify client HTTP handling in your Silverlight application, you can get and set the cookies associated with the requests and responses. This topic demonstrates how to get and set cookies on HTTP requests and responses when using client HTTP handling.

Note Note:

For information about how to specify HTTP handling, see How to: Specify Browser or Client HTTP Handling.

Note Note:

If the server sends HTTPOnly cookies, you should create a System.Net.CookieContainer on the request to hold the cookies, although you will not see or be able to access the cookies that are stored in the container. If you do not create a container to hold the cookies, the request will fail. For more information on HTTPOnly cookies, see HTTPOnly cookies..

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://api.search.live.net"),
        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.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();
                }
            }
    
        }
    }
    
    
    

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.

Run this sample


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>


  • In Visual Studio, create a new Silverlight Application project named CookiesEx. Make sure that you choose the default project option, which is to host the Silverlight application in a new Web site.

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

  • Add a reference to System.Windows.Controls assembly.

Community Additions

ADD
Show:
© 2014 Microsoft