我在这里看过 C# WebRequest using Cookies Multiple WebRequest in same session Reuse Connection with HttpWebRequest in C# C# keep session id over httpwebrequest
这就是我正在做的事情,除了我希望将我的 CookieContainer 作为成员(名为 session_cookie)存储在我的名为 connector 的类中。我的问题是,如果我在代码中使用临时对象,那么 cookie 可以正常工作:
CookieContainer t = new CookieContainer();
HTTPReq = (HttpWebRequest)WebRequest.Create(scriptURL);
HTTPReq.CookieContainer = t;
但是如果我使用
HTTPReq = (HttpWebRequest)WebRequest.Create(scriptURL);
HTTPReq.CookieContainer = session_cookie;
然后就不行了!我不知道为什么
这是连接器类代码:
public class Connector
{
public CookieContainer session_cookie;
private string session_id;
private HttpWebRequest HTTPReq;
private HttpWebResponse Response;
//Session oriented connection
public string serverRequest(string scriptURL, string payLoad)
{
try
{
HTTPReq = (HttpWebRequest)WebRequest.Create(scriptURL);
HTTPReq.CookieContainer = session_cookie;
HTTPReq.Method = "POST";
//Data arguments
byte[] byteArray = Encoding.UTF8.GetBytes(payLoad);
HTTPReq.ContentType = "application/x-www-form-urlencoded";
HTTPReq.ContentLength = byteArray.Length;
//Get the stream to write into
Stream dataStream = HTTPReq.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
Response = (HttpWebResponse)HTTPReq.GetResponse();
Encoding enc = Encoding.GetEncoding(1252); // Western latin alphabet (windows default)
//Get the repsonse from the server
StreamReader ResponseStream = new StreamReader(Response.GetResponseStream(), enc);
string response = ResponseStream.ReadToEnd().Trim();
Response.Close();
ResponseStream.Close();
return response;
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
return null;
}
}
}
有任何想法吗?