@@ -31,6 +31,11 @@ public class HttpClient : IHttpClient
3131 /// </summary>
3232 private long pendingCount = 0L ;
3333
34+ /// <summary>
35+ /// 是否支持创建Handler
36+ /// </summary>
37+ private bool supportCreateHandler = false ;
38+
3439 /// <summary>
3540 /// 获取关联的Http处理对象
3641 /// </summary>
@@ -81,10 +86,46 @@ public long MaxResponseContentBufferSize
8186 /// <summary>
8287 /// 默认的HttpClient
8388 /// </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 )
85102 {
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 ) ;
88129 }
89130
90131 /// <summary>
@@ -198,6 +239,10 @@ private void InitWithoutProxy()
198239 /// <returns></returns>
199240 protected virtual HttpClientHandler CreateHttpClientHandler ( )
200241 {
242+ if ( this . supportCreateHandler == false )
243+ {
244+ throw new NotSupportedException ( "不支持创建新的HttpClientHandler实例" ) ;
245+ }
201246 return new DefaultHttpClientHandler ( ) ;
202247 }
203248
0 commit comments