Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
Cookie Class

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
Cookie Class

Provides a set of properties and methods that are used to manage cookies. This class cannot be inherited.

Namespace:  System.Net
Assembly:  System (in System.dll)
Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class Cookie
Visual Basic (Usage)
Dim instance As Cookie
C#
[SerializableAttribute]
public sealed class Cookie
Visual C++
[SerializableAttribute]
public ref class Cookie sealed
JScript
public final class Cookie

The Cookie class is used by a client application to retrieve information about cookies that are received with HTTP responses. The following cookie formats are supported during parsing of the HTTP response headers: the original Netscape specification, RFC 2109, and RFC 2965.

For a list of initial property values for an instance of Cookie, see the various Cookie constructors.

The following example sends a request to a URL and displays the cookies returned in the response.

Visual Basic
Imports System.Net
Imports System

' This example is run at the command line.
' Specify one argument: the name of the host to 
' receive the request.
' If the request is sucessful, the example displays the contents of the cookies
' returned by the host.

Public Class CookieExample

    Public Shared Sub Main(args() As String)
        If args Is Nothing OrElse args.Length <> 1 Then
            Console.WriteLine("Specify the URL to receive the request.")
            Environment.Exit(1)
        End If
        Dim request As HttpWebRequest = CType(WebRequest.Create(args(0)), HttpWebRequest)
        request.CookieContainer = New CookieContainer()

        Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)



        ' Print the properties of each cookie.
        Dim cook As Cookie
        For Each cook In  response.Cookies
            Console.WriteLine("Cookie:")
            Console.WriteLine("{0} = {1}", cook.Name, cook.Value)
            Console.WriteLine("Domain: {0}", cook.Domain)
            Console.WriteLine("Path: {0}", cook.Path)
            Console.WriteLine("Port: {0}", cook.Port)
            Console.WriteLine("Secure: {0}", cook.Secure)

            Console.WriteLine("When issued: {0}", cook.TimeStamp)
            Console.WriteLine("Expires: {0} (expired? {1})", cook.Expires, cook.Expired)
            Console.WriteLine("Don't save: {0}", cook.Discard)
            Console.WriteLine("Comment: {0}", cook.Comment)
            Console.WriteLine("Uri for comments: {0}", cook.CommentUri)
            Console.WriteLine("Version: RFC {0}", IIf(cook.Version = 1, "2109", "2965"))

            ' Show the string representation of the cookie.
            Console.WriteLine("String: {0}", cook.ToString())
        Next cook
    End Sub 'Main
End Class 'CookieExample 



' Output from this example will be vary depending on the host name specified,
' but will be similar to the following.
'
'Cookie:
'CustomerID = 13xyz
'Domain: .contoso.com
'Path: /
'Port:
'Secure: False
'When issued: 1/14/2003 3:20:57 PM
'Expires: 1/17/2013 11:14:07 AM (expired? False)
'Don't save: False
'Comment: 
'Uri for comments:
'Version: RFC 2965
'String: CustomerID = 13xyz
'


C#
using System.Net;
using System;
namespace Examples.System.Net.Cookies
{
    // This example is run at the command line.
    // Specify one argument: the name of the host to 
    // send the request to.
    // If the request is sucessful, the example displays the contents of the cookies
    // returned by the host.

    public class CookieExample
    {   
        public static void Main(string[] args)
        {   
            if (args == null || args.Length != 1)
            {
                Console.WriteLine("Specify the URL to receive the request.");
                Environment.Exit(1);
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
            request.CookieContainer = new CookieContainer();

            HttpWebResponse response = (HttpWebResponse) request.GetResponse();



            // Print the properties of each cookie.
            foreach (Cookie cook in response.Cookies)
            {
                Console.WriteLine("Cookie:");
                Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
                Console.WriteLine("Domain: {0}", cook.Domain);
                Console.WriteLine("Path: {0}", cook.Path);
                Console.WriteLine("Port: {0}", cook.Port);
                Console.WriteLine("Secure: {0}", cook.Secure);

                Console.WriteLine("When issued: {0}", cook.TimeStamp);
                Console.WriteLine("Expires: {0} (expired? {1})", 
                    cook.Expires, cook.Expired);
                Console.WriteLine("Don't save: {0}", cook.Discard);    
                Console.WriteLine("Comment: {0}", cook.Comment);
                Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
                Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

                // Show the string representation of the cookie.
                Console.WriteLine ("String: {0}", cook.ToString());
            }
        }
    }
}

// Output from this example will be vary depending on the host name specified,
// but will be similar to the following.
/*
Cookie:
CustomerID = 13xyz
Domain: .contoso.com
Path: /
Port:
Secure: False
When issued: 1/14/2003 3:20:57 PM
Expires: 1/17/2013 11:14:07 AM (expired? False)
Don't save: False
Comment: 
Uri for comments:
Version: RFC 2965
String: CustomerID = 13xyz
*/


Visual C++
#using <System.dll>

using namespace System;
using namespace System::Net;

// This example is run at the command line.
// Specify one argument: the name of the host to 
// send the request to.
// If the request is sucessful, the example displays the contents of the cookies
// returned by the host.
int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();
   if ( args == nullptr || args->Length != 2 )
   {
      Console::WriteLine( "Specify the URL to receive the request." );
      Environment::Exit( 1 );
   }


   HttpWebRequest^ request = dynamic_cast<HttpWebRequest^>(WebRequest::Create( args[ 1 ] ));
   request->CookieContainer = gcnew CookieContainer;
   HttpWebResponse^ response = dynamic_cast<HttpWebResponse^>(request->GetResponse());
   response->Cookies = request->CookieContainer->GetCookies( request->RequestUri );

   // Print the properties of each cookie.
   System::Collections::IEnumerator^ myEnum = response->Cookies->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Cookie^ cook = safe_cast<Cookie^>(myEnum->Current);
      Console::WriteLine( "Cookie:" );
      Console::WriteLine( "{0} = {1}", cook->Name, cook->Value );
      Console::WriteLine( "Domain: {0}", cook->Domain );
      Console::WriteLine( "Path: {0}", cook->Path );
      Console::WriteLine( "Port: {0}", cook->Port );
      Console::WriteLine( "Secure: {0}", cook->Secure );
      Console::WriteLine( "When issued: {0}", cook->TimeStamp );
      Console::WriteLine( "Expires: {0} (expired? {1})", cook->Expires, cook->Expired );
      Console::WriteLine( "Don't save: {0}", cook->Discard );
      Console::WriteLine( "Comment: {0}", cook->Comment );
      Console::WriteLine( "Uri for comments: {0}", cook->CommentUri );
      Console::WriteLine( "Version: RFC {0}", cook->Version == 1 ? (String^)"2109" : "2965" );

      // Show the string representation of the cookie.
      Console::WriteLine( "String: {0}", cook );

   }

}

// Output from this example will be vary depending on the host name specified,
// but will be similar to the following.
/*
Cookie:
CustomerID = 13xyz
Domain: .contoso.com
Path: /
Port:
Secure: False
When issued: 1/14/2003 3:20:57 PM
Expires: 1/17/2013 11:14:07 AM (expired? False)
Don't save: False
Comment: 
Uri for comments:
Version: RFC 2965
String: CustomerID = 13xyz
*/

System..::.Object
  System.Net..::.Cookie
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Cookies Sample written in PowerShell      Thomas Lee   |   Edit   |   Show History
<#
.SYNOPSIS
This script gets and displays the cookies returned from a site.
.DESCRIPTION
This script calls System.Net.WebRequest to get a page. in the
response there may be cookies returned which this script then
displays. By default, the cookies returned from the MSDN home page
are displayed. To improve production orientation, the creation of
the request and getting the response are protected by try/catch
blocks.
.NOTES
File Name : get-cookie.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell V2 CTP3

.LINK
This script posted to:
http://www.pshscripts.blogspot.com
MSDN Sample posted at:
http://msdn.microsoft.com/en-us/library/system.net.cookie.aspx
.EXAMPLE
PSH [C:\foo]: . 'C:\Users\tfl\AppData\Local\Temp\Untitled4.ps1'
3 Cookies returned from: http://www.microsoft.com/msdn

Cookie:
A = I&I=AxUFAAAAAADmCwAA/fh06TVFlKw6GSuBKKj6Yg!!&M=1
Domain : .microsoft.com
Path : /
Port :
Secure : False
When issued : 6/7/2009 10:06:30 AM
Expires :
Expired? : False
Don't save : False
Comment :
Uri for comments:
Version : 0
String: A=I&I=AxUFAAAAAADmCwAA/fh06TVFlKw6GSuBKKj6Yg!!&M=1 :

Cookie:
ADS = SN=175A21EF
Domain : .microsoft.com
Path : /
Port :
Secure : False
When issued : 6/7/2009 10:06:30 AM
Expires :
Expired? : False
Don't save : False
Comment :
Uri for comments:
Version : 0
String: ADS=SN=175A21EF :

Cookie:
mediaRssUrl = http://www.microsoft.com/feeds/msdn/en-us/HDI/Home-HDI.xml
Domain : msdn.microsoft.com
Path : /
Port :
Secure : False
When issued : 6/7/2009 10:06:30 AM
Expires :
Expired? : False
Don't save : False
Comment :
Uri for comments:
Version : 0
String: mediaRssUrl=http://www.microsoft.com/feeds/msdn/en-us/HDI/Home-HDI.xml :
#>
param (
$site = "http://www.microsoft.com/msdn"
)

##
# Start of script
##

# Create the web request object, catching any errors
try {
$request = [System.Net.WebRequest]::Create($site)
$request.CookieContainer = New-Object System.Net.CookieContainer
}
catch {
"Error creating request";$requst
return
}

# Now get response
try {
$response = $request.GetResponse()
}
catch {
"Error getting respoinse from $site - try later"
return
}

# Print number of cookies
if ($response.Cookies.Count -gt 0) {
"{0} Cookies returned from: {1}" -f $Response.Cookies.Count,$site
""
}

# Print the properties of each cookie.
foreach ($cook in $Response.Cookies) {
"Cookie:"
"{0} = {1}" -f $cook.Name, $cook.Value
"Domain : {0}" -f $cook.Domain
"Path : {0}" -f $cook.Path
"Port : {0}" -f $cook.Port
"Secure : {0}" -f $cook.Secure
"When issued : {0}" -f $cook.TimeStamp
"Expires : {0}" -f $cook.expireds
"Expired? : {0}" -f $cook.expired
"Don't save : {0}" -f $cook.Discard
"Comment : {0}" -f $cook.Comment
"Uri for comments: {0}" -f $cook.CommentUri
"Version : {0}" -f $cook.Version
"String: {0} :" -f $cook.ToString()
""
}
# End of Script
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker