Cookie Question

W

William

ERROR:

Exception Details: System.NullReferenceException: Object reference not set
to an instance of an object.

This if then statement only works if a cookie exists.
It fails if the cookie does not exist.
How can I turn off lines 2 to 9 if a cookie does not exist (ie: if the
cookies does not exist then create one)?

CODE:

1 If Request.Cookies("visitor") is Nothing Then
2 dim cookie as HttpCookie
3 cookie=new HttpCookie("visitor")
4 cookie.Values.Add("cid", Session("sid"))
5 cookie.Values.Add("ckeywords",Session("skeywords"))
6 cookie.Values.Add("ccampaignno",Session("scampaignno"))
7 cookie.Values.Add("cadgroup",Session("sadgroup"))
8 cookie.Expires = Now.AddDays(365)
9 response.appendcookie(cookie)
10 end if
 
A

arunprakashb

This is a sample code from the MCP book.

If Request.Browser.Cookies Then
' (2) If the cookie does not exist...
If Request.Cookies("LastVisit") Is Nothing Then
' (3) Create the cookie.
Dim cookLastVisit As New HttpCookie("LastVisit", _
DateTime.Now.ToString())
' (4) Set the expiration to tommorrow.
cookLastVisit.Expires = DateTime.Now.AddDays(1)
' (5) Add to cookies collection.
Response.Cookies.Add(cookLastVisit)
' Display message.
litMessage.Text = "This is your first visit."
Else
' Get the cookie.
Dim cookLastVisit As HttpCookie = Request.Cookies("LastVisit")

' Display a message showing time of last visit.
litMessage.Text = "You last visited this page: " & _
cookLastVisit.Value
' Update the cookie on the client.
Response.Cookies("LastVisit").Value = Now.ToString()
Response.Cookies("LastVisit").Expires =
DateTime.Now.AddDays(1)
End If
Else
litMessage.Text = "Your browser does not accept cookies."
End If


Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top