【问题标题】:C# HttpWebRequest CookieContainer/Collection persisting between Object instances?C# HttpWebRequest CookieContainer/Collection 在对象实例之间持续存在?
【发布时间】:2011-07-18 06:16:43
【问题描述】:

我的登录程序遇到了问题。如果我登录一次,然后为 null CookieContainer 和 CookieCollection(以及我的 http 类),然后尝试再次登录,它仍然会从第一个请求中提交 cookie。为什么饼干粘在身边?

例子:

HTTP uh;

MainWindow()
{
    uh = new HTTP(); 
    uh.login("mySite"); 
    //Logging in....
    //Login Successful.....

    uh.cookieContainer = null;
    uh.cookieCollection = null;
    uh = null; 
    uh = new HTTP(); 
    uh.loging("mySite");
    //Logging in, with cookies from first login
    //Login Fails.....

}

编辑: HTTP 类的粗略表示...

public class HTTP()
{   
    public CookieContainer cookieContainer;
    public CookieCollection cookieCollection;
    private HttpWebRequest Request;
    private HttpWebResponse Response;

    public HTTP()
    {
        this.cookieContainer = new CookieContainer();
        this.cookieCollection = new CookieCollection();
    }

    public HttpWebResponse login(string url)
    {
        string[] cred = new string[2] { "un", "pw" };

        this.Request = (HttpWebRequest)HttpWebRequest.Create(url);
        this.Request.CookieContainer = cookieContainer;
        byte[] ByteArray = Encoding.UTF8.GetBytes(String.Format("un={0}&pw={1}", cred));
        this.Request.ContentLength = ByteArray.Length;
        Stream DataStream = this.Request.GetRequestStream();
        DataStream.Write(ByteArray, 0, ByteArray.Length);
        DataStream.Close();
        Response = (HttpWebResponse)this.Request.GetResponse();
        this.cookieCollection = Response.Cookies;

        return Response; 
    }

    public bool responseHandle(HttpWebResponse r) 
    {
        //Determines success, logs headers, html body, etc..
    }
}

编辑 |解决方案: 上面的任何代码都没有问题。我犯了一个愚蠢的错误,没有将HTTP null/new 代码放在我的注销按钮中。所以它从来没有重置过。很抱歉浪费了大家的时间。

【问题讨论】:

  • 您必须提供HTTP 类的实现才能做出任何判断。
  • 感谢您的分享,它对我帮助很大。

标签: c# cookies httpwebrequest cookiecontainer


【解决方案1】:

当您使用完 cookie 后,它就会过期,它就会消失。 (又名,将其过期日期设置为经过的时间)。

【讨论】:

  • 这可能行得通...但它似乎很hackish...没有冒犯...老实说我不喜欢这种可能的解决方案。另外,这可能会导致其他错误,具体取决于我稍后提出请求的方式。
  • 感谢您的帮助,我发现了问题所在并发布在上面。但是,因为您用技术上正确的方法回答了我的问题,所以我接受它作为答案。感谢您的宝贵时间和帮助!
猜你喜欢
  • 2013-11-08
  • 1970-01-01
  • 2016-11-06
  • 1970-01-01
  • 1970-01-01
  • 2014-04-08
  • 1970-01-01
  • 2013-01-24
  • 1970-01-01
相关资源
最近更新 更多