Skip to content

Instantly share code, notes, and snippets.

@damianh
Created April 28, 2018 11:43
Show Gist options
  • Save damianh/038195c1ab0c5013ad3883d7e3c59d99 to your computer and use it in GitHub Desktop.
Save damianh/038195c1ab0c5013ad3883d7e3c59d99 to your computer and use it in GitHub Desktop.
HttpMessageHandler for dealing with cookies in requests.
public class CookieMessageHandler : DelegatingHandler
{
private readonly CookieContainer _cookies = new CookieContainer();
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Headers.Add("Cookie", _cookies.GetCookieHeader(request.RequestUri));
var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (response.Headers.TryGetValues("Set-Cookie", out var newCookies))
{
foreach (var item in SetCookieHeaderValue.ParseList(newCookies.ToList()))
{
var uri = new Uri(request.RequestUri, item.Path.Value);
_cookies.Add(uri, new Cookie(item.Name.Value, item.Value.Value, item.Path.Value));
}
}
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment