I have implemented a custom HttpMessageHandler that tracks cookies.
It uses reflection to invoke the actual handler and simply reads / sets the cookie headers.
class TestMessageHandler : HttpMessageHandler { delegate Task<HttpResponseMessage> HandlerSendAsync(HttpRequestMessage message, CancellationToken token); private readonly HandlerSendAsync nextDelegate; private readonly CookieContainer cookies = new System.Net.CookieContainer(); public TestMessageHandler(HttpMessageHandler next) { if(next == null) throw new ArgumentNullException(nameof(next)); nextDelegate = (HandlerSendAsync) next.GetType() .GetTypeInfo() .GetMethod("SendAsync", BindingFlags.NonPublic | BindingFlags.Instance) .CreateDelegate(typeof(HandlerSendAsync), next); } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { request.Headers.Add("Cookie", cookies.GetCookieHeader(request.RequestUri)); var resp = await nextDelegate(request, cancellationToken).ConfigureAwait(false); if (resp.Headers.TryGetValues("Set-Cookie", out var newCookies)) { foreach (var item in SetCookieHeaderValue.ParseList(newCookies.ToList())) { cookies.Add(request.RequestUri, new Cookie(item.Name, item.Value, item.Path)); } } return resp; } }
And then you create your HttpClient as follows:
var httpClient = new HttpClient( new TestMessageHandler( server.CreateHandler()));
TestMessageHandler now tracks cookies.
source share