0

我正在使用 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?
}
4

1 回答 1

1

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

下面是一个来自 msdn 的示例,说明如何在 C# 中执行此操作(不确定您使用的是哪种语言)。

if (Request.Cookies["UserSettings"] != null)
{
    HttpCookie myCookie = new HttpCookie("UserSettings");
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);
}
于 2010-04-09T21:18:44.447 回答