This documentation is archived and is not being maintained.

HttpListenerResponse.SetCookie Method

Adds or updates a Cookie in the collection of cookies sent with this response.

Namespace:  System.Net
Assembly:  System (in System.dll)

'Declaration
Public Sub SetCookie ( _
	cookie As Cookie _
)

Parameters

cookie
Type: System.Net.Cookie
A Cookie for this response.

ExceptionCondition
ArgumentNullException

cookie is Nothing.

ArgumentException

The cookie already exists in the collection and could not be replaced.

Two cookies are considered the same if the values of their Name, Domain, and Path properties are the same. If these three pieces of information are the same, the method attempts to update the cookie. The name and domain comparisons are not case sensitive, but the path comparison is case sensitive.

The following code example demonstrates calling this method.


' This example requires the System and System.Net namespaces.
Public Shared Sub SimpleCookieExample(ByVal prefixes() As String)
    ' Create a listener.
    Dim listener As New HttpListener()
    ' Add the prefixes.
    For Each s As String In prefixes
        listener.Prefixes.Add(s)
    Next s
    listener.Start()
    Console.WriteLine("Listening...")
    ' Note: The GetContext method blocks while waiting for a request. 
    Dim context As HttpListenerContext = listener.GetContext()
    Dim request As HttpListenerRequest = context.Request

    ' This application sends a cookie to the client marking the time 
    ' they visited. 
    Dim timeStampCookie As New Cookie("VisitDate", Date.Now.ToString())
    ' Obtain a response object.
    Dim response As HttpListenerResponse = context.Response
    ' Add the cookie to the response.
    response.SetCookie(timeStampCookie)
    ' Construct a response.
    Dim responseString As String = "<HTML><BODY> Hello world!</BODY></HTML>"
    response.ContentEncoding = System.Text.Encoding.UTF8
    Dim buffer() As Byte = System.Text.Encoding.UTF8.GetBytes(responseString)
    ' Send the response.
    response.Close(buffer, True)
    listener.Stop()
End Sub


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Show: