Skip to content

Instantly share code, notes, and snippets.

@wislon
Created September 10, 2015 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wislon/f802a80135dae3900950 to your computer and use it in GitHub Desktop.
Save wislon/f802a80135dae3900950 to your computer and use it in GitHub Desktop.
Get Cookies from HTTPClient instance (using CookieContainer, or raw headers)
/// <summary>
/// Will return null if the cookie you were looking for isn't in the container.
/// </summary>
/// <param name="cookieName"></param>
/// <param name="cookieContainer"></param>
/// <returns></returns>
protected async Task<Cookie> ExtractCookieWithName(string cookieName, CookieContainer cookieContainer)
{
var cookies = cookieContainer.GetCookies(new Uri(SharedConstants.WebsiteBaseUrl));
var cookie = cookies[cookieName];
return await Task.FromResult(cookie);
}
protected async Task<Cookie> ExtractNamedCookieFromRawHeaders(string cookieName, HttpResponseHeaders responseHeaders)
{
IEnumerable<string> newCookies;
if (!responseHeaders.TryGetValues("Set-Cookie", out newCookies)) { return null; }
string cookieString = newCookies.FirstOrDefault(nc => nc.Contains(cookieName));
if (string.IsNullOrWhiteSpace(cookieString)) { return null; }
var cookieStringElements = cookieString.Substring(cookieString.IndexOf(cookieName, StringComparison.OrdinalIgnoreCase))
.Split(new char[] { '=', ';' }, StringSplitOptions.RemoveEmptyEntries);
int valueIndex = cookieStringElements.ToList().IndexOf(cookieName) + 1;
string value = cookieStringElements[valueIndex];
const string path = "/";
string domain = new Uri(SharedConstants.WebsiteBaseUrl).DnsSafeHost;
{
return await Task.FromResult(new Cookie(cookieName, value, path, domain));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment