私は自分のDelegatingHandler
ためにクッキーを管理するものを書きました。およびCookieContainer
で簡単に使用できるように、いくつかの拡張メソッドも作成しました。HttpRequestMessage
HttpResponseMessage
internal class DangerouslySimpleCookieContainer : DelegatingHandler {
internal DangerouslySimpleCookieContainer(CookieContainer cookieContainer = null) {
this.Container = cookieContainer ?? new CookieContainer();
}
internal DangerouslySimpleCookieContainer(HttpMessageHandler innerHandler, CookieContainer cookieContainer = null)
: base(innerHandler) {
this.Container = cookieContainer ?? new CookieContainer();
}
public CookieContainer Container { get; set; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
this.Container.ApplyCookies(request);
var response = await base.SendAsync(request, cancellationToken);
this.Container.SetCookies(response);
return response;
}
}
internal static class CookieContainerExtensions {
internal static void SetCookies(this CookieContainer container, HttpResponseMessage response, Uri requestUri = null) {
Requires.NotNull(container, "container");
Requires.NotNull(response, "response");
IEnumerable<string> cookieHeaders;
if (response.Headers.TryGetValues("Set-Cookie", out cookieHeaders)) {
foreach (string cookie in cookieHeaders) {
container.SetCookies(requestUri ?? response.RequestMessage.RequestUri, cookie);
}
}
}
internal static void ApplyCookies(this CookieContainer container, HttpRequestMessage request) {
Requires.NotNull(container, "container");
Requires.NotNull(request, "request");
string cookieHeader = container.GetCookieHeader(request.RequestUri);
if (!string.IsNullOrEmpty(cookieHeader)) {
request.Headers.TryAddWithoutValidation("Cookie", cookieHeader);
}
}
}