Reputation: 107
I have the following Cookies in headers
Cookie: ASP.NET_SessionId=cm3bg4muwin1vmbovc1esjy3; host=SCANDICWEB101; ieAlertDisplay=true; scandic_lb_cookie=1702298890.0.0000; s_sv_sid=110733906247;
This is my code to get the first one
var sessionId = webResponse.Headers["Set-Cookie"].Split(';')
.First(s => s.StartsWith("ASP.NET_SessionId="));
I tried to get the host
, scandic_lb_cookie
and the rest as well, but I couldnt figure out a way to do it, could you suggest me some ideas to get them?
Upvotes: 2
Views: 3935
Reputation: 363
You should be able to iterate over cookie properties. Check HttpWebResponse Cookie property and How To: Get and Set Cookies on MSDN. There is no need to do any complex string operation.
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;
}
Upvotes: 1
Reputation: 23093
Possibly there are faster solutions, but following should work:
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() });
Then you can use them like:
foreach(var val in parts)
{
string name = val.Name;
string value = val.Value;
}
Or if you like it as a 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());
and then
string host = parts["host"];
See complete and working LINQPad example HERE.
Upvotes: 2
Reputation: 67898
What about this:
var sessionId = webResponse.Headers["Set-Cookie"]
.Split(';')
.Where(s => s.StartsWith("scandic_lb_cookie="));
Upvotes: 0