clear cookie container in WebRequest

Jeremy picture Jeremy · Apr 9, 2010 · Viewed 7.4k times · Source

I'm using the WebRequest object to post data to a login page, then post data to a seperate page on the same site. I am instantiating a CookieContainer and assigning it to the WebRequest object so that the cookies are handled. The problem is that I do not want to retain the cookie after I post data to the other page. How can I delete that cookie?

private CookieContainer cookie_m;
protected CookieContainer CookieContainer
{
    get
    {
        if (cookie_m == null)
        {
            cookie_m = new CookieContainer();
        }
        return cookie_m;
    }
    set
    {
        cookie_m = value;
    }
}

protected virtual void SetData(WebRequest request, string sData)
{
    if (!String.IsNullOrEmpty(sData))
    {
        byte[] binPostData = System.Text.Encoding.ASCII.GetBytes(sData);
        request.ContentLength = binPostData.Length;
        System.IO.Stream sRequest = request.GetRequestStream();
        try
        {
            sRequest.Write(binPostData, 0, binPostData.Length);
        }
        finally
        {
            sRequest.Close();
        }
    }
}

private HttpWebRequest GetNewRequest(string sUrl)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sUrl);
    request.CookieContainer = this.CookieContainer;
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";

    return request;
}

public override void Submit()
{
    //Login 
    HttpWebRequest request = GetNewRequest("http://mytest/login.asp");

    base.SetData(request, "action=validate_login&login=test&password=test");
    WebResponse response = request.GetResponse();

    System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
    string sResponse = sr.ReadToEnd();

    //Entry screen
    request = GetNewRequest("http://mytest/CustCreate.asp");
    base.SetData(request, "Site=xyz&Cust=test");
    response = request.GetResponse();

    sr = new System.IO.StreamReader(response.GetResponseStream());
    sResponse = sr.ReadToEnd();

    //Sutmit
    request = request = GetNewRequest("http://mytest/CustCreate.asp");
    base.SetData(request, "Site=xyz&mydatahere&B1=Submit");
    response = request.GetResponse();

    sr = new System.IO.StreamReader(response.GetResponseStream());
    sResponse = sr.ReadToEnd();

    //How to delete cookies that have been saved?
}

Answer

Shawn Steward picture Shawn Steward · Apr 9, 2010

To delete a cookie, you need to set the expiration date on it to a date in the past. This tells the browser it's expired and the browser will delete it.

Here's an example from msdn on how to do this in C# (not sure which language you're using).

if (Request.Cookies["UserSettings"] != null)
{
    HttpCookie myCookie = new HttpCookie("UserSettings");
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);
}