2016-11-25 141 views
0

我的C#應用​​程序正在網站上做一些工作。我想在每次運行我的應用程序時使用相同的cookie,而不是創建新的cookie。我想將cookie保存到數據庫或序列化它。存儲和檢索cookie

的代碼是:

CookieContainer cookie = new CookieContainer(); 

private string getRequest(string url, CookieContainer cookie, string postData = "") 
{ 
    System.Net.ServicePointManager.Expect100Continue = true; 
    StreamReader reader; 

    var request = WebRequest.Create(url) as HttpWebRequest; 
    request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14"; 
    request.CookieContainer = cookie; 
    request.AllowAutoRedirect = true; 
    request.ContentType = "application/x-www-form-urlencoded"; 
    request.Headers.Add("X-Requested-With", "XMLHttpRequest"); 

    postData = Uri.EscapeUriString(postData); 

    request.Method = "POST"; 
    request.ContentLength = postData.Length; 

    Stream requestStream = request.GetRequestStream(); 
    Byte[] postBytes = Encoding.ASCII.GetBytes(postData); 

    requestStream.Write(postBytes, 0, postBytes.Length); 
    requestStream.Close(); 

    HttpWebResponse response = request.GetResponse() as HttpWebResponse; 

    foreach (Cookie tempCookie in response.Cookies) 
    { 
     cookie.Add(tempCookie); 
    } 

    reader = new StreamReader(response.GetResponseStream()); 
    string readerReadToEnd = reader.ReadToEnd(); 
    response.Close(); 

    foreach (Cookie _cookie in response.Cookies) 
    { 
     Console.WriteLine("1. Version: {0}", _cookie.Version); 
     Console.WriteLine("2. Value: {0}", _cookie.Value); 
     Console.WriteLine("3. TimeStamp: {0}", _cookie.TimeStamp); 
     Console.WriteLine("4. Secure: {0}", _cookie.Secure); 
     Console.WriteLine("5. Port: {0}", _cookie.Port); 
     Console.WriteLine("6. Path: {0}", _cookie.Path); 
     Console.WriteLine("7. Name: {0}", _cookie.Name); 
     Console.WriteLine("8. HttpOnly: {0}", _cookie.HttpOnly); 
     Console.WriteLine("9. Expires: {0}", _cookie.Expires); 
     Console.WriteLine("10. Expired: {0}", _cookie.Expired); 
     Console.WriteLine("11. Domain: {0}", _cookie.Domain); 
     Console.WriteLine("12. Discard: {0}", _cookie.Discard); 
     Console.WriteLine("13. CommentUri: {0}", _cookie.CommentUri); 
     Console.WriteLine("14. Comment: {0}", _cookie.Comment); 
     Console.WriteLine("String: {0}", _cookie.ToString()); 
    } 

    return readerReadToEnd; 
} 

當我運行我的應用程序,我用的cookie相同的情況下工作。但是當我再次運行應用程序時,cookie是不同的。我想總是使用同一個。

控制檯輸出給了我這樣的:

1. Version: 0 
2. Value: rujd49p08kthfcuf7itdgnhkap5jideg 
3. TimeStamp: 2016-11-25 21:58:06 
4. Secure: False 
5. Port: 
6. Path:/
7. Name: PHPSESSID 
8. HttpOnly: True 
9. Expires: 0001-01-01 00:00:00 
10. Expired: False 
11. Domain: example-site.com 
12. Discard: False 
13. CommentUri: 
14. Comment: 
String: PHPSESSID=rujd49p08kthfcuf7itdgnhkap5jideg 

所以我的問題是:我能救我的cookie,並使用相同的cookie例如1天后?

回答

0

可以使用序列化CookieContainer到磁盤BinaryFormatter

var bf = new BinaryFormatter(); 
var wstr = File.OpenWrite(@"C:\some\location\cookies.bin"); 
bf.Serialize(wstr, cookieContainer); 
wstr.Close(); 

然後你可以閱讀收集從保存的文件重新應用的更高運行(或每當):

var rstr = File.OpenRead(@"C:\some\location\cookies.bin"); 
var cookieContainer = (CookieContainer)new BinaryFormatter().Deserialize(rstr); 

然後你可以分配反序列化的CookieContainer的HttpWebRequest.CookieContainer你讓你的請求之前,它會使用存儲的cookie - 如果這些cookie不會過期b Ÿ您嘗試再次使用它們的時間。

你提到的PHPSESSID cookie是沒有明確的終止會話cookie - 你可以保存並重新使用它,你想在這裏的方式,但它仍然只是實際工作只要在服務器上的PHP認爲會話有效。

此外,你應該不需要做這在你的代碼:

foreach (Cookie tempCookie in response.Cookies) 
{ 
    cookie.Add(tempCookie); 
} 

你已經設置request.CookieContainer = cookie在你的代碼(其中cookieCookieContainer) - 與完成,在收到的餅乾響應自動進入CookieContainer,您不需要手動執行此操作。

+0

哇,謝謝你的回答。我想知道是否有任何方法將我的cookie存儲在SQL Server數據庫中,例如通過保存爲字節。你有什麼經驗嗎? – Dawvawd

+0

有很多方法可以將序列化表示存儲在SQL中: – bookdev

+0

您仍然使用BinaryFormatter,但是您要寫入一個'MemoryStream',然後調用'ToArray()'來獲取數組序列化表示的原始字節。從那裏你可以將它存儲在SQL的'binary' /'varbinary'字段中,或者你可以調用'Convert.ToBase64String(bytes)'把它變成一個base64字符串,可以存儲在一個普通的'varchar'中,或者'nvarchar'字段,然後用'FromBase64String()'轉回到字節數組形式。您最終可以使用BinaryFormatter將您的'CookieContainer'序列化/反序列化爲任何類型的流。 – bookdev