Skip to content

Commit ad715e3

Browse files
committed
增加KeepCookieContainer配置
1 parent 8b84462 commit ad715e3

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

WebApiClient/HttpApiFactory.cs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Net;
23
using System.Net.Http;
34
using System.Threading;
45

@@ -37,6 +38,16 @@ public class HttpApiFactory<TInterface> : IHttpApiFactory<TInterface>, IHttpApiF
3738
/// </summary>
3839
private readonly InterceptorCleaner interceptorCleaner = new InterceptorCleaner();
3940

41+
/// <summary>
42+
/// 是否保持cookie容器
43+
/// </summary>
44+
private bool keepCookieContainer = true;
45+
46+
/// <summary>
47+
/// cookie容器
48+
/// </summary>
49+
private CookieContainer cookieContainer;
50+
4051
/// <summary>
4152
/// HttpApi创建工厂
4253
/// </summary>
@@ -77,6 +88,18 @@ public HttpApiFactory<TInterface> SetCleanupInterval(TimeSpan interval)
7788
return this;
7889
}
7990

91+
/// <summary>
92+
/// 设置是维护一个CookieContainer实例
93+
/// 该实例为首次创建时的CookieContainer
94+
/// </summary>
95+
/// <param name="keep">true则共用同一个CookieContainer</param>
96+
/// <returns></returns>
97+
public HttpApiFactory<TInterface> SetKeepCookieContainer(bool keep)
98+
{
99+
this.keepCookieContainer = keep;
100+
return this;
101+
}
102+
80103
/// <summary>
81104
/// 配置HttpMessageHandler的创建
82105
/// </summary>
@@ -132,6 +155,13 @@ private LifetimeInterceptor CreateInterceptor()
132155
this.configAction.Invoke(httpApiConfig);
133156
}
134157

158+
if (this.keepCookieContainer == true)
159+
{
160+
var handlerContainer = httpApiConfig.HttpHandler.CookieContainer;
161+
Interlocked.CompareExchange(ref this.cookieContainer, handlerContainer, null);
162+
httpApiConfig.HttpHandler.CookieContainer = this.cookieContainer;
163+
}
164+
135165
return new LifetimeInterceptor(
136166
httpApiConfig,
137167
this.lifeTime,

0 commit comments

Comments
 (0)