首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

wininet.dll 實作永不過期 Cookie:InternetSetCookie / InternetGetCookie

     編輯:關於ASP.NET

P/Invoke 宣告

[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetCookie(string url, string name, string data);

[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetGetCookie(string url, string name, StringBuilder data, ref int size);

完整流程:讀取既有 Cookie → 刪除舊檔 → 重寫並設定遠期 Expires

// 1. 取得現有 Cookie
var cookie = new StringBuilder(2048);
int size = cookie.Length;
InternetGetCookie("https://www.example.com", null, cookie, ref size);

// 2. 刪除本地 Cookie 檔案 (可選,視需求)
foreach (var file in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Cookies))) {
    if (file.ToLower().Contains("example")) File.Delete(file);
}

// 3. 重寫並加上 Expires=2099 年
foreach (var pair in cookie.ToString().Split(';')) {
    var kv = pair.Split('=');
    string name = kv[0].Trim();
    string value = kv[1].Trim() + ";expires=Sun, 22-Feb-2099 00:00:00 GMT";
    InternetSetCookie("https://www.example.com", name, value);
    // 若有多子域名,逐一設定
    InternetSetCookie("https://forum.example.com", name, value);
}

適用場景

  • 自動化測試需長期保持登入狀態。
  • 爬蟲/整合工具模擬持久會話。
  • **注意**:直接操作 IE Cookie 存儲,僅影響 IE/Edge (舊版) 與使用 wininet 的應用,不影響 Chrome/Firefox。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved