Cookie not found on first load of asp.net-page

Discussion in 'C#' started by marpeto, Aug 10, 2008.

  1. #1
    I'm an newbie on cookies, and theres probably some basics I haven't learned yet...

    I want to remember some info about the visitor, so the visitor don't have to rekey it the next time he/she visits - so I create a cookie. The cookie is beeing used during the visit, and after the visits the cookie really exits. But when I return to the site next day my asp.net-page dont recognize that there is a cookie on the first page_load, but if I press F5/reloads the page it will be found and after that there is no cookie-problem during the session.

    Is there a way to get my ASP.net-page to get hands on the cookie on the first page_load?
     
    marpeto, Aug 10, 2008 IP
  2. vihutuo

    vihutuo Well-Known Member

    Messages:
    1,511
    Likes Received:
    34
    Best Answers:
    0
    Trophy Points:
    180
    #2
    Maybe if you post some code it will be easier to solve
     
    vihutuo, Aug 10, 2008 IP
  3. marpeto

    marpeto Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    If Not Page.IsPostBack Then 'Skip if page has been redisplayed caused by an error
    'Is there a Cooke?
    If Not Request.Cookies("MyCookie") Is Nothing Then
    'The Cookie exist! Get cookie values...
    Else
    'The cookie doesn't exist! - Create default values...
    End If
    End If

    Any ideas? Must I change to "If Request.Cookies("MyCookie") Is Nothing Then"... and switch the code in the IF-statements?
     
    marpeto, Aug 10, 2008 IP
  4. vihutuo

    vihutuo Well-Known Member

    Messages:
    1,511
    Likes Received:
    34
    Best Answers:
    0
    Trophy Points:
    180
    #4
    After you create the cookie, you need to set the expiration date or else the cookie will expire as soon as the user's session is over. Set the cookie's expiration after creating the cookie as follows
    Request.Cookies("MyCookie").Expires = DateTime.Now.AddDays(30)
     
    vihutuo, Aug 10, 2008 IP
  5. marpeto

    marpeto Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks - seems to do the trick! I did the expire "to early" - before I saved the cookie - in the creation of the cookie.
     
    marpeto, Aug 10, 2008 IP
  6. vihutuo

    vihutuo Well-Known Member

    Messages:
    1,511
    Likes Received:
    34
    Best Answers:
    0
    Trophy Points:
    180
    #6
    Welcome :)
     
    vihutuo, Aug 11, 2008 IP