Create guid cookie in global.asa

Posted on 2011-10-03
Last Modified: 2013-12-16
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);

Question by:bongii
    LVL 17

    Accepted Solution

    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);

    Open in new window


    Author Comment

    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);
    LVL 17

    Expert Comment

    by:Carlos Villegas
    You are right dude, if the cookie don't exist in the Response.Cookies collection it will be created.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to improve team productivity

    Quip adds documents, spreadsheets, and tasklists to your Slack experience
    - Elevate ideas to Quip docs
    - Share Quip docs in Slack
    - Get notified of changes to your docs
    - Available on iOS/Android/Desktop/Web
    - Online/Offline

    Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
    This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
    This video is in connection to the article "The case of a missing mobile phone (". It will help one to understand clearly the steps to track a lost android phone.
    In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

    758 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now