Replacing a Cookie instance

Posted on 2007-09-29
Last Modified: 2008-01-09
According to MS, the CookieContainer.SetCookies Method "ADDS Cookie instances for one or more cookies from an HTTP cookie header to the CookieContainer for a specific URI," but what if I wanted to REPLACE a Cookie instance?  The below creates two instances of the same header.  I just want one.

Uri uri = new Uri(url);

// displays "MyCookie: MyValue"

MyHttpRequest.CookieContainer.SetCookies(uri,"MyCookie: MyNewValue);

// displays "MyCookie: MyNewValue; MyCookie: MyValue," rather than just "MyCookie: MyNewValue"
Question by:arichexe
    LVL 51

    Expert Comment

    The Request object is what you received from the client.  If you want to send a cookie back you need to use the Response object

    Author Comment

    How would I code that?
    LVL 51

    Accepted Solution

    // Add a new cookie
    HttpCookie myCookie = new HttpCookie("UserSettings");
    myCookie["Font"] = "Arial";
    myCookie["Color"] = "Blue";
    myCookie.Expires = DateTime.Now.AddDays(1d);

    // Write to an existing cookie
    Response.Cookies["UserSettings"]["Font"] = "Arial";
    Response.Cookies["UserSettings"]["Color"] = "Blue";
    Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(1d);


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Training Course: Java/J2EE and SOA

    This course will cover both core and advanced Java concepts like Database connectivity, Threads, Exception Handling, Collections, JSP, Servlets, XMLHandling, and more. You'll also learn various Java frameworks like Hibernate and Spring.

    Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
    Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
    This video discusses moving either the default database or any database to a new volume.
    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…

    779 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