我将cookie导出到Json文件中.看起来是这样的:

[
    {
        "name": "abc",
        "value": "0000",
        "domain": ".domain.com",
        "hostOnly": false,
        "path": "/",
        "secure": false,
        "httpOnly": false,
        "sameSite": "no_restriction",
        "session": false,
        "firstPartyDomain": "",
        "partitionKey": null,
        "expirationDate": 1734526188,
        "storeId": null
    },
    {
        "name": "dfg",
        "value": "777",
        "domain": ".domain.it",
        "hostOnly": false,
        "path": "/",
        "secure": true,
        "httpOnly": true,
        "sameSite": "no_restriction",
        "session": false,
        "firstPartyDomain": "",
        "partitionKey": null,
        "expirationDate": 1684947948,
        "storeId": null
    }
]

如您所见,有些值是strings,例如name、hostOnly是boolean、partitionKey是nullable、expirationDate是integer.

这是我使用的C代码

json = File.ReadAllText("json.txt");
JArray array = JArray.Parse(json);

foreach(JObject cookie_json in array)
{
      foreach(var entry in cookie_json)
      {
         cookies.Add(new Cookie(entry.Key, (string?)entry.Value));
      }
 }

但在这里,我发现了几个错误:

  1. Cookie()构造函数只接受字符串作为Value,所以我不能添加整数、布尔值和不可为null的元素,因为可为null的元素会引发异常
  2. 我正在 for each 条目(行)而不是每个Json元素(代表一个Cookie)创建一个新Cookie.我怎样才能解决这个问题?

推荐答案

我可以看到您的逻辑-如果深入到openqa.selenium.cookie,您可以看到他们是如何实现构造函数的:

        public Cookie(string name, string value, string domain, string path, DateTime? expiry)
        public Cookie(string name, string value, string path, DateTime? expiry)
        public Cookie(string name, string value, string path)
        public Cookie(string name, string value)

您不需要添加cookie的每个单独部分-您可以通过一次声明所有值来创建cookie.

cookie中的所有值都是字符串,因此您只需要输入.toString()个和非字符串值.

看看你的JSON——我不知道你是怎么得到storeID的.

The object structure on the selenium cookie can't handle it: cookieobject

您还可以通过控制台中的JS直接添加/操作Cookie,大约document.cookie = "MyName=myValue;StoreId=123"

But when you add unrecognised values it just rips them out: devtoolsconsole

可能是它自己的cookies 但现在我只是在猜测.

Csharp相关问答推荐

ListaryImportProperty的默认DllImportSearchPathsProperty行为

一种安全的方式来存储SSH凭证(MAUI/C#应用程序)

将轮询与超时同步

Take()方法如何与IAsyncEnumerable一起使用

在路由中使用枚举

使用可信第三方的Iext8.Net pdf签名

如何使用NumberFormatInfo

当前代码Cosmos DB 3.37.1:PartitionKey key key mismatch exception

什么时候接受(等待)信号灯?尽可能的本地化?

JsonSchema.Net删除假阳性判断结果

Regex字母数字校验

是否可以将Collectionview中的数组与ObservableCollection绑定?

在扩展方法中,IEnumerable<;T>;不会转换为IEumerable<;T&>

如何对特定异常使用Polly重试机制?

如何使用.NET 8.0中新的CompositeFormat类?

嵌套Blazor组件内的验证

实体框架允许您具有筛选的属性吗?

为什么我的UserControl没有加载到我的主窗口中?

实例化列表时的集合表达式是什么?

将带有嵌套If-Else的Foreach循环转换为Linq表达式