我在标题中有以下Cookie
Cookie:ASP.NET_SessionId = cm3bg4muwin1vmbovc1esjy3; HOST = SCANDICWEB101; ieAlertDisplay = TRUE; scandic_lb_cookie = 1702298890.0.0000; s_sv_sid = 110733906247;
这是我获得第一个
的代码var sessionId = webResponse.Headers["Set-Cookie"].Split(';')
.First(s => s.StartsWith("ASP.NET_SessionId="));
我试图获得host
,scandic_lb_cookie
以及其余部分,但我无法找到一种方法来做到这一点,你能给我一些想法吗?
答案 0 :(得分:1)
可能有更快的解决方案,但以下应该有效:
string source = cookie.Substring(8); // remove the "Cookie: "
var parts = source.Split(';')
.Where(i => i.Contains("=")) // filter out empty values
.Select(i => i.Trim().Split('=')) // trim to remove leading blank
.Select(i => new { Name = i.First(), Value = i.Last() });
然后你可以使用它们:
foreach(var val in parts)
{
string name = val.Name;
string value = val.Value;
}
或者如果您喜欢Dictionary<string, string>
:
string source = coockie.Substring(8); // remove the "Cookie: "
var parts = source.Split(';')
.Where(i => i.Contains("="))
.Select(i => i.Trim().Split('='))
.ToDictionary(i => i.First(), i => i.Last());
然后
string host = parts["host"];
查看完整且有效的LINQPad示例HERE。
答案 1 :(得分:1)
您应该能够遍历cookie属性。在MSDN上查看HttpWebResponse Cookie property和How To: Get and Set Cookies。无需进行任何复杂的字符串操作。
private void ReadCookies()
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://gmail.com");
request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Console.WriteLine(response.Headers.ToString());
//Console.WriteLine(response.StatusCode.GetHashCode());
CookieCollection IncomingCookies = response.Cookies;
Console.WriteLine("Listing out {0} cookies received.", IncomingCookies.Count);
foreach(Cookie cookie in IncomingCookies)
{
Console.WriteLine("{0} = {1}", cookie.Name, cookie.Value);
}
return;
}
答案 2 :(得分:0)
这个怎么样:
var sessionId = webResponse.Headers["Set-Cookie"]
.Split(';')
.Where(s => s.StartsWith("scandic_lb_cookie="));