@@ -31,6 +31,11 @@ public class HttpClient : IHttpClient
31
31
/// </summary>
32
32
private long pendingCount = 0L ;
33
33
34
+ /// <summary>
35
+ /// 是否支持创建Handler
36
+ /// </summary>
37
+ private bool supportCreateHandler = false ;
38
+
34
39
/// <summary>
35
40
/// 获取关联的Http处理对象
36
41
/// </summary>
@@ -81,10 +86,46 @@ public long MaxResponseContentBufferSize
81
86
/// <summary>
82
87
/// 默认的HttpClient
83
88
/// </summary>
84
- public HttpClient ( )
89
+ public HttpClient ( ) :
90
+ this ( handler : null , disposeHandler : true , supportCreateHandler : true )
91
+ {
92
+ }
93
+
94
+ /// <summary>
95
+ /// 默认的HttpClient
96
+ /// </summary>
97
+ /// <param name="handler">关联的Http处理对象</param>
98
+ /// <param name="disposeHandler">调用Dispose方法时,是否也Dispose handler</param>
99
+ /// <exception cref="ArgumentNullException"></exception>
100
+ public HttpClient ( HttpClientHandler handler , bool disposeHandler = false )
101
+ : this ( handler , disposeHandler , false )
85
102
{
86
- this . Handler = this . CreateHttpClientHandler ( ) ;
87
- this . client = new System . Net . Http . HttpClient ( this . Handler ) ;
103
+ }
104
+
105
+ /// <summary>
106
+ /// 默认的HttpClient
107
+ /// </summary>
108
+ /// <param name="handler"></param>
109
+ /// <param name="disposeHandler">调用HttpClient.Dispose时是否也disposeHandler</param>
110
+ /// <param name="supportCreateHandler">是否支持调用创建实例</param>
111
+ /// <exception cref="ArgumentNullException"></exception>
112
+ private HttpClient ( HttpClientHandler handler , bool disposeHandler , bool supportCreateHandler )
113
+ {
114
+ this . supportCreateHandler = supportCreateHandler ;
115
+ if ( handler == null )
116
+ {
117
+ if ( supportCreateHandler == false )
118
+ {
119
+ throw new ArgumentNullException ( nameof ( handler ) ) ;
120
+ }
121
+ else
122
+ {
123
+ handler = this . CreateHttpClientHandler ( ) ;
124
+ }
125
+ }
126
+
127
+ this . Handler = handler ;
128
+ this . client = new System . Net . Http . HttpClient ( this . Handler , disposeHandler ) ;
88
129
}
89
130
90
131
/// <summary>
@@ -198,6 +239,10 @@ private void InitWithoutProxy()
198
239
/// <returns></returns>
199
240
protected virtual HttpClientHandler CreateHttpClientHandler ( )
200
241
{
242
+ if ( this . supportCreateHandler == false )
243
+ {
244
+ throw new NotSupportedException ( "不支持创建新的HttpClientHandler实例" ) ;
245
+ }
201
246
return new DefaultHttpClientHandler ( ) ;
202
247
}
203
248
0 commit comments