Condividi tramite


How to: Get and Set Cookies

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

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.

NoteNote:

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

NoteNote:

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()
    
    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"))
    
    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()
    
    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.

    ' 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 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();
                }
            }
    
        }
    }
    

Example

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

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>

Compiling the Code

  • 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.