C# HttpWebRequest CookieContainer/Collection 在对象实例之间持久存在?

标签 c# cookies httpwebrequest cookiecontainer

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

示例:

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..
    }
}

编辑 |解决方案: 上面any代码没有问题。我犯了一个愚蠢的错误,没有将 HTTP 空/新代码放在我的注销按钮中。所以它永远不会重置。抱歉浪费大家的时间。

最佳答案

用完后让 cookie 过期,它就会消失。 (又名,将其过期日期设置为耗时)。

关于C# HttpWebRequest CookieContainer/Collection 在对象实例之间持久存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5353999/

相关文章:

c# - 在 WPF 中查看 Word 文档

google-chrome - Chrome 和 Firefox 认为第三方 cookie 的规则是什么?

cookies - 使用 postman 发送cookie

vba - ExcelVBA - 通过 MSXML2.XMLHTTP 的 HttpReq - 加载页面后获取页面

asp.net-mvc - 如何在 .net MVC 中创建安全的每个 Web 请求事务?

c# - 使用 C# 删除 XML 标记

c# - 帮助 C#.NET 通用集合性能和优化

c# - 将业务逻辑暴露给任务调度机制的架构正确且安全的方法是什么

php - 如何防止 Javascript 访问 PHP cookie 数据?

java - 将 HTTP 响应(Java "Properties"流格式)转换为 NSDictionary