在WebRequest中清除cookie容器

时间:2010-04-09 21:11:53

标签: cookies httpwebrequest webrequest cookiecontainer

我正在使用WebRequest对象将数据发布到登录页面,然后将数据发布到同一站点上的单独页面。我正在实例化一个CookieContainer并将其分配给WebRequest对象,以便处理cookie。问题是我在将数据发布到其他页面后不想保留cookie。如何删除该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?
}

1 个答案:

答案 0 :(得分:1)

要删除Cookie,您需要将其上的截止日期设置为过去的日期。这告诉浏览器它已过期,浏览器将删除它。

这是关于如何在C#中执行此操作的example from msdn(不确定您使用的是哪种语言)。

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