GetCookie extract information to a String

后端 未结 1 748
旧时难觅i
旧时难觅i 2021-01-07 10:50

I\'m trying to get the numbers information from a cookie I get by Set-Cookie I need &om=-&lv=1341532178340&xrs= the numbers here

This is wha

相关标签:
1条回答
  • 2021-01-07 11:24

    With first loop, you are building an ArrayList that contains Cookie instances. It's not possible to simply convert from Cookie to string as you are attempting to do just before the second loop.

    A simple way to get values of all cookies is to use LINQ:

    IEnumerable<string> cookieValues = agent.LastResponse.Cookies.Select(x => x.Value);
    

    If you are still using .NET Framework 2.0, you will need to use a loop:

    List<string> cookieValues = new List<string>();
    foreach (Cookie cookie in agent.LastResponse.Cookies)
    {
        cookieValues.Add(cookie.Value);
    }
    

    Then, you can iterate over this collection just like you previously were. However, are you aware that if multiple cookies match your regex, the last one that matches will be stored to the key? Don't know how exactly you want this to work when there are multiple cookies that match, but if you simply want the first one, you can again employ LINQ to make your code simpler and do almost everything you need in a single query:

    var cookies = agent.LastResponse.Cookies;
    string key = cookies.Cast<Cookie>()
        .Select(x => Regex.Match(x.Value, @"&lv=(.*)&xrs=", RegexOptions.IgnoreCase))
        .Where(x => x.Success)
        .Select(x => x.Groups[1].Value)
        .FirstOrDefault();
    

    If there was no match, the key will be null, otherwise, it will contain the first match. The Cast<Cookie>() bit is necessary for type inference to kick in - I believe that agent.LastResponse.Cookies returns an instance of CookieCollection which does not implement IEnumerable<Cookie>.

    0 讨论(0)
提交回复
热议问题