设置和获取cookie

如何:获取和设置 Cookie

如果在 Silverlight 应用程序中指定客户端 HTTP 处理,则可以获取和设置与请求和响应关联的 Cookie。 本主题演示使用客户端 HTTP 处理时,如何获取和设置 HTTP 请求和响应上的 Cookie。

注意说明:

有关如何指定 HTTP 处理的信息,请参见如何指定浏览器或客户端 HTTP 处理

注意说明:

如果服务器发送 HTTPOnly Cookie,则应在请求上创建一个 System.Net..::.CookieContainer 用于保存 Cookie,尽管将无法看到或访问该容器中存储的 Cookie。 如果不创建容器来保存 Cookie,则请求将失败。 有关 HTTPOnly Cookie 的更多信息,请参见HTTPOnly cookies. (HTTPOnly Cookie)。

设置请求消息上的 Cookie

  1. HttpWebRequestHttpWebRequest..::.CookieContainer 属性创建一个System.Net..::.CookieContainer 对象。

    
    request.CookieContainer = New CookieContainer()
    
    
    
            
    1. request.CookieContainer = new CookieContainer();
    2.  
  2. 使用 CookieContainer..::.Add 方法将 Cookie 对象添加到HttpWebRequest..::.CookieContainer

    
    request.CookieContainer.Add(New Uri("http://api.search.live.net"), _
        New Cookie("id", "1234"))
    
    
    
            
    1. request.CookieContainer.Add(new Uri("http://api.search.live.net"),
    2.     new Cookie("id""1234"));
    3.  

获取响应消息上的 Cookie

  1. 在请求上创建一个 System.Net..::.CookieContainer 以保存对响应发送的 Cookie 对象。 即使没有发送任何 Cookie 也必须执行此操作。

    
    request.CookieContainer = New CookieContainer()
    
    
    
            
    1. request.CookieContainer = new CookieContainer();
    2.  
  2. 检索 HttpWebResponseHttpWebResponse..::.Cookies 属性中的值。 在此示例中,将检索 Cookie 并将它们保存到独立存储中。

    
    ' 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
    
    
    
            
    1. private void ReadCallback(IAsyncResult asynchronousResult)
    2. {
    3.     HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
    4.     HttpWebResponse response = (HttpWebResponse)
    5.         request.EndGetResponse(asynchronousResult);
    6.     using (IsolatedStorageFile isf =
    7.         IsolatedStorageFile.GetUserStoreForSite())
    8.     {
    9.         using (IsolatedStorageFileStream isfs = isf.OpenFile("CookieExCookies",
    10.             FileMode.OpenOrCreate, FileAccess.Write))
    11.         {
    12.             using (StreamWriter sw = new StreamWriter(isfs))
    13.             {
    14.                 foreach (Cookie cookieValue in response.Cookies)
    15.                 {
    16.                     sw.WriteLine("Cookie: " + cookieValue.ToString());
    17.                 }
    18.                 sw.Close();
    19.             }
    20.         }
    21.  
    22.     }
    23. }
    24.  
示例

下面的示例演示如何创建 Web 请求并向该请求添加 Cookie。 此示例还演示如何从 Web 响应提取 Cookie,如何将 Cookie 写入独立存储中的文件以及从独立存储中进行读取。 运行此示例时,将在TextBlock 控件中显示System.Net..::.Cookie 值。

运行此示例


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


       
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Documents;
  8. using System.Windows.Input;
  9. using System.Windows.Media;
  10. using System.Windows.Media.Animation;
  11. using System.Windows.Shapes;
  12. using System.Net.Browser;
  13. using System.IO;
  14. using System.Text;
  15. using System.IO.IsolatedStorage;
  16.  
  17.  
  18. namespace CookiesEx
  19. {
  20.     public partial class MainPage : UserControl
  21.     {
  22.         public MainPage()
  23.         {
  24.             InitializeComponent();
  25.  
  26.         }
  27.  
  28.         private void button1_Click(object sender, RoutedEventArgs e)
  29.         {
  30.             InitializeWebRequestClientStackForURI();
  31.             ReadFromIsolatedStorage();
  32.         }
  33.  
  34.         private void InitializeWebRequestClientStackForURI()
  35.         {
  36.             // Create the client WebRequest creator.
  37.             IWebRequestCreate creator = WebRequestCreator.ClientHttp;
  38.  
  39.             // Register both http and https.
  40.             WebRequest.RegisterPrefix("http://", creator);
  41.             WebRequest.RegisterPrefix("https://", creator);
  42.  
  43.  
  44.             // Create a HttpWebRequest.
  45.             HttpWebRequest request = (HttpWebRequest)
  46.                 WebRequest.Create("http://api.search.live.net/clientaccesspolicy.xml");
  47.  
  48.             //Create the cookie container and add a cookie.
  49.             request.CookieContainer = new CookieContainer();
  50.  
  51.  
  52.             // This example shows manually adding a cookie, but you would most
  53.             // likely read the cookies from isolated storage.
  54.             request.CookieContainer.Add(new Uri("http://api.search.live.net"),
  55.                 new Cookie("id""1234"));
  56.  
  57.             // Send the request.
  58.             request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
  59.         }
  60.  
  61.         // Get the response and write cookies to isolated storage.
  62.         private void ReadCallback(IAsyncResult asynchronousResult)
  63.         {
  64.             HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
  65.             HttpWebResponse response = (HttpWebResponse)
  66.                 request.EndGetResponse(asynchronousResult);
  67.             using (IsolatedStorageFile isf =
  68.                 IsolatedStorageFile.GetUserStoreForSite())
  69.             {
  70.                 using (IsolatedStorageFileStream isfs = isf.OpenFile("CookieExCookies",
  71.                     FileMode.OpenOrCreate, FileAccess.Write))
  72.                 {
  73.                     using (StreamWriter sw = new StreamWriter(isfs))
  74.                     {
  75.                         foreach (Cookie cookieValue in response.Cookies)
  76.                         {
  77.                             sw.WriteLine("Cookie: " + cookieValue.ToString());
  78.                         }
  79.                         sw.Close();
  80.                     }
  81.                 }
  82.  
  83.             }
  84.         }
  85.         private void ReadFromIsolatedStorage()
  86.         {
  87.             using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite())
  88.             {
  89.                 using (IsolatedStorageFileStream isfs =
  90.                    isf.OpenFile("CookieExCookies", FileMode.Open))
  91.                 {
  92.                     using (StreamReader sr = new StreamReader(isfs))
  93.                     {
  94.                         tb1.Text = sr.ReadToEnd();
  95.                         sr.Close();
  96.                     }
  97.                 }
  98.  
  99.             }
  100.         }
  101.  
  102.  
  103.     }
  104. }
  105.  

<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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值