[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 545
  • Last Modified:

Create guid cookie in global.asa

Hi Guys.

Why do I get an error when I tryes to create my guid user cookie in global.asa?
If i paste the code to default.aspx, it works?

  void Application_Start(object sender, EventArgs e)
    {
         if (Request.Cookies["Guid"] == null)
        {
            Response.Cookies["Guid"].Value = System.Guid.NewGuid().ToString();
            Response.Cookies["Guid"].Expires = DateTime.Now.AddYears(2);
        }

    }
0
Jesper Christensen
Asked:
Jesper Christensen
  • 2
1 Solution
 
Carlos VillegasFull Stack .NET DeveloperCommented:
Hello, that will give you a null reference exception, try:
if (Request.Cookies["Guid"] == null)
{
    HttpCookie myCookie = new HttpCookie("Guid", System.Guid.NewGuid().ToString());
    myCookie.Expires = DateTime.Now.AddYears(2);
    Response.Cookies.Add(myCookie);
}

Open in new window

0
 
Jesper ChristensenAuthor Commented:
Hi.
Thank you.
But the error was, that the code was in Application_Start. I have moved the code to Session_Start and now it works.

So this will not give a null reference :)
Response.Cookies["Guid"].Value = System.Guid.NewGuid().ToString();
Response.Cookies["Guid"].Expires = DateTime.Now.AddYears(2);
0
 
Carlos VillegasFull Stack .NET DeveloperCommented:
You are right dude, if the cookie don't exist in the Response.Cookies collection it will be created.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now