我自己编写了一个DelegatingHandler
为我管理 cookie 的程序。我还写了几个扩展方法,CookieContainer
以便可以轻松地与HttpRequestMessage
and一起使用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);
}
}
}