Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cookies collection bug? 1

Status
Not open for further replies.

chpicker

Programmer
Apr 10, 2001
1,316
0
0
Can anyone explain to me why this code does not work in VB.NET?
Code:
[COLOR=blue]For Each[/color] myCookie [COLOR=blue]As[/color blue] HttpCookie [COLOR=blue]In[/color] HttpContext.Current.Request.Cookies
This line gives a Server Error: Unable to cast object of type 'System.String' to type 'System.Web.HttpCookie'.

If I change it to "As String" the line works.

Why is Request.Cookies a collection of strings and not a collection of cookies? IntelliSense tells me it's a collection of cookies, but it's not.

How can I do a simple iteration through the cookies for name/value pairs?

Version Information: Microsoft .NET Framework Version 2.0.50727.42; ASP.NET Version 2.0.50727.210

Ian
 
Try this:

Code:
Imports System.Net
        Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
        For Each myCookie As Cookie In  response.Cookies

Senior Software Developer
 
IntelliSense tells me it's a collection of cookies
Actually, it doesn't. It tells you that it returns a HttpCookieCollection which as you've found out is a collection of Strings. This can be proved by running this:
Code:
        Dim iEnum As IEnumerator = Request.Cookies.GetEnumerator()
        While iEnum.MoveNext
            Response.Write(iEnum.Current.GetType.ToString)
        End While
So, taking your previous example, you can just use the String to get the relevant cookie from the Cookies collection e.g.
Code:
        Dim c As HttpCookie
        For Each myCookie As String In HttpContext.Current.Request.Cookies
            c = Request.Cookies.Item(myCookie)
            ...
        Next


-------------------------------------------------------

Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]
[URL unfurl="true"]http://mdssolutions.co.uk[/url] - Delivering professional ASP.NET solutions
[URL unfurl="true"]http://weblogs.asp.net/marksmith[/url]
 
So, the strings in the collection are the NAMES of the cookies? That should get me what I need. Thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top