You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AngleSharp中正确设置Cookie?Criticker登录状态无法保持

问题分析与解决方案

核心原因

你通过document.Cookie获取的Cookie不完整——JS无法访问HttpOnly类型的Cookie,而绝大多数网站的登录会话Cookie都是HttpOnly(用于防止XSS攻击)。这导致你保存的Cookie里缺少维持登录状态的关键标识,自然无法复用。另外,直接保存document.Cookie字符串会丢失Cookie的属性信息(如Domain、Path、HttpOnly、Secure等),服务器收到不完整的Cookie后会拒绝识别。

解决步骤

1. 从AngleSharp的Cookie容器完整提取Cookie(包括HttpOnly)

登录成功后,不要用JS获取Cookie,直接从AngleSharp内置的Cookie提供者中提取所有Cookie:

// 登录成功后获取所有Cookie
var cookieProvider = context.Configuration.Services.GetRequiredService<ICookieProvider>();
var cookies = cookieProvider.GetCookies(new Url("https://www.criticker.com"));

// 将Cookie的完整属性序列化到文件(示例用JSON)
var cookieData = cookies.Select(c => new {
    Name = c.Name,
    Value = c.Value,
    Domain = c.Domain,
    Path = c.Path,
    Expires = c.Expires,
    HttpOnly = c.HttpOnly,
    Secure = c.Secure
}).ToList();
File.WriteAllText("criticker_cookies.json", JsonSerializer.Serialize(cookieData));

2. 启动时完整恢复Cookie

下次启动应用时,读取保存的Cookie数据,逐个还原到AngleSharp的Cookie容器中:

// 创建上下文(保持配置一致,比如User-Agent要和登录时相同)
var config = AngleSharp.Configuration.Default
    .WithDefaultLoader()
    .WithJs()
    .WithDefaultCookies();
var context = BrowsingContext.New(config);

// 读取并还原Cookie
var cookieData = JsonSerializer.Deserialize<List<JsonElement>>(File.ReadAllText("criticker_cookies.json"));
var cookieProvider = context.Configuration.Services.GetRequiredService<ICookieProvider>();
foreach (var cookieProps in cookieData)
{
    var cookie = new Cookie(
        cookieProps.GetProperty("Name").GetString(),
        cookieProps.GetProperty("Value").GetString(),
        cookieProps.GetProperty("Domain").GetString(),
        cookieProps.GetProperty("Path").GetString(),
        cookieProps.GetProperty("Expires").GetDateTimeOffset(),
        cookieProps.GetProperty("Secure").GetBoolean(),
        cookieProps.GetProperty("HttpOnly").GetBoolean()
    );
    cookieProvider.SetCookie(new Url("https://www.criticker.com"), cookie);
}

// 打开页面验证登录状态
var document = await context.OpenAsync("https://www.criticker.com");

3. 额外注意事项

  • 保持User-Agent一致:网站可能通过User-Agent识别客户端,确保登录和后续请求的User-Agent相同,可在配置中添加:
    .WithDefaultLoader(l => l.WithUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"))
    
  • 验证Cookie发送:可添加请求拦截器,检查发送到服务器的Cookie是否和Chrome中一致:
    config.With(request => {
        Console.WriteLine("Request Cookie: " + request.Headers["Cookie"]);
        return request;
    });
    

内容的提问来源于stack exchange,提问作者morphinapg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 20:13:00