存储和检索cookie

时间:2016-11-25 21:07:58

标签: c# cookies session-cookies

我的C#app正在网站上做一些工作。每次运行我的应用程序时,我都想使用相同的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天后吗?

1 个答案:

答案 0 :(得分: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在您到期时未过期试图再次使用它们。

你提到的PHPSESSID cookie是没有明确到期的会话cookie - 你可以保存并以你想要的方式重复使用它,但它仍然只能工作只要服务器上的PHP认为该会话有效。

此外,您不需要在代码中执行此操作:

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

您已在代码中设置了request.CookieContainer = cookie(其中cookieCookieContainer) - 完成后,响应中收到的Cookie会自动放入CookieContainer 1}},您不需要手动执行此操作。