我的登录程序遇到了问题。如果我登录一次,然后将 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/