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.

    
    ' 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
    
    
    

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



<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