This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
HttpClient.cs
755 lines (642 loc) · 29 KB
/
HttpClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public class HttpClient : HttpMessageInvoker
{
#region Fields
private static IWebProxy s_defaultProxy;
private static readonly TimeSpan s_defaultTimeout = TimeSpan.FromSeconds(100);
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
private static readonly TimeSpan s_infiniteTimeout = Threading.Timeout.InfiniteTimeSpan;
private const HttpCompletionOption defaultCompletionOption = HttpCompletionOption.ResponseContentRead;
private volatile bool _operationStarted;
private volatile bool _disposed;
private CancellationTokenSource _pendingRequestsCts;
private HttpRequestHeaders _defaultRequestHeaders;
private Version _defaultRequestVersion = HttpUtilities.DefaultRequestVersion;
private Uri _baseAddress;
private TimeSpan _timeout;
private int _maxResponseContentBufferSize;
#endregion Fields
#region Properties
public static IWebProxy DefaultProxy
{
get => LazyInitializer.EnsureInitialized(ref s_defaultProxy, () => SystemProxyInfo.Proxy);
set
{
s_defaultProxy = value ?? throw new ArgumentNullException(nameof(value));
}
}
public HttpRequestHeaders DefaultRequestHeaders
{
get
{
if (_defaultRequestHeaders == null)
{
_defaultRequestHeaders = new HttpRequestHeaders();
}
return _defaultRequestHeaders;
}
}
public Version DefaultRequestVersion
{
get => _defaultRequestVersion;
set
{
CheckDisposedOrStarted();
_defaultRequestVersion = value ?? throw new ArgumentNullException(nameof(value));
}
}
public Uri BaseAddress
{
get { return _baseAddress; }
set
{
CheckBaseAddress(value, nameof(value));
CheckDisposedOrStarted();
if (NetEventSource.IsEnabled) NetEventSource.UriBaseAddress(this, value);
_baseAddress = value;
}
}
public TimeSpan Timeout
{
get { return _timeout; }
set
{
if (value != s_infiniteTimeout && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_timeout = value;
}
}
public long MaxResponseContentBufferSize
{
get { return _maxResponseContentBufferSize; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
if (value > HttpContent.MaxBufferSize)
{
throw new ArgumentOutOfRangeException(nameof(value), value,
SR.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize));
}
CheckDisposedOrStarted();
Debug.Assert(HttpContent.MaxBufferSize <= int.MaxValue);
_maxResponseContentBufferSize = (int)value;
}
}
#endregion Properties
#region Constructors
public HttpClient()
: this(new HttpClientHandler())
{
}
public HttpClient(HttpMessageHandler handler)
: this(handler, true)
{
}
public HttpClient(HttpMessageHandler handler, bool disposeHandler)
: base(handler, disposeHandler)
{
_timeout = s_defaultTimeout;
_maxResponseContentBufferSize = HttpContent.MaxBufferSize;
_pendingRequestsCts = new CancellationTokenSource();
}
#endregion Constructors
#region Public Send
#region Simple Get Overloads
public Task<string> GetStringAsync(string requestUri) =>
GetStringAsync(CreateUri(requestUri));
public Task<string> GetStringAsync(Uri requestUri) =>
GetStringAsyncCore(GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead));
private async Task<string> GetStringAsyncCore(Task<HttpResponseMessage> getTask)
{
// Wait for the response message.
using (HttpResponseMessage responseMessage = await getTask.ConfigureAwait(false))
{
// Make sure it completed successfully.
responseMessage.EnsureSuccessStatusCode();
// Get the response content.
HttpContent c = responseMessage.Content;
if (c != null)
{
#if NET46
return await c.ReadAsStringAsync().ConfigureAwait(false);
#else
HttpContentHeaders headers = c.Headers;
// Since the underlying byte[] will never be exposed, we use an ArrayPool-backed
// stream to which we copy all of the data from the response.
using (Stream responseStream = c.TryReadAsStream() ?? await c.ReadAsStreamAsync().ConfigureAwait(false))
using (var buffer = new HttpContent.LimitArrayPoolWriteStream(_maxResponseContentBufferSize, (int)headers.ContentLength.GetValueOrDefault()))
{
try
{
await responseStream.CopyToAsync(buffer).ConfigureAwait(false);
}
catch (Exception e) when (HttpContent.StreamCopyExceptionNeedsWrapping(e))
{
throw HttpContent.WrapStreamCopyException(e);
}
if (buffer.Length > 0)
{
// Decode and return the data from the buffer.
return HttpContent.ReadBufferAsString(buffer.GetBuffer(), headers);
}
}
#endif
}
// No content to return.
return string.Empty;
}
}
public Task<byte[]> GetByteArrayAsync(string requestUri) =>
GetByteArrayAsync(CreateUri(requestUri));
public Task<byte[]> GetByteArrayAsync(Uri requestUri) =>
GetByteArrayAsyncCore(GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead));
private async Task<byte[]> GetByteArrayAsyncCore(Task<HttpResponseMessage> getTask)
{
// Wait for the response message.
using (HttpResponseMessage responseMessage = await getTask.ConfigureAwait(false))
{
// Make sure it completed successfully.
responseMessage.EnsureSuccessStatusCode();
// Get the response content.
HttpContent c = responseMessage.Content;
if (c != null)
{
#if NET46
return await c.ReadAsByteArrayAsync().ConfigureAwait(false);
#else
HttpContentHeaders headers = c.Headers;
using (Stream responseStream = c.TryReadAsStream() ?? await c.ReadAsStreamAsync().ConfigureAwait(false))
{
long? contentLength = headers.ContentLength;
Stream buffer; // declared here to share the state machine field across both if/else branches
if (contentLength.HasValue)
{
// If we got a content length, then we assume that it's correct and create a MemoryStream
// to which the content will be transferred. That way, assuming we actually get the exact
// amount we were expecting, we can simply return the MemoryStream's underlying buffer.
buffer = new HttpContent.LimitMemoryStream(_maxResponseContentBufferSize, (int)contentLength.GetValueOrDefault());
try
{
await responseStream.CopyToAsync(buffer).ConfigureAwait(false);
}
catch (Exception e) when (HttpContent.StreamCopyExceptionNeedsWrapping(e))
{
throw HttpContent.WrapStreamCopyException(e);
}
if (buffer.Length > 0)
{
return ((HttpContent.LimitMemoryStream)buffer).GetSizedBuffer();
}
}
else
{
// If we didn't get a content length, then we assume we're going to have to grow
// the buffer potentially several times and that it's unlikely the underlying buffer
// at the end will be the exact size needed, in which case it's more beneficial to use
// ArrayPool buffers and copy out to a new array at the end.
buffer = new HttpContent.LimitArrayPoolWriteStream(_maxResponseContentBufferSize);
try
{
try
{
await responseStream.CopyToAsync(buffer).ConfigureAwait(false);
}
catch (Exception e) when (HttpContent.StreamCopyExceptionNeedsWrapping(e))
{
throw HttpContent.WrapStreamCopyException(e);
}
if (buffer.Length > 0)
{
return ((HttpContent.LimitArrayPoolWriteStream)buffer).ToArray();
}
}
finally { buffer.Dispose(); }
}
}
#endif
}
// No content to return.
return Array.Empty<byte>();
}
}
// Unbuffered by default
public Task<Stream> GetStreamAsync(string requestUri)
{
return GetStreamAsync(CreateUri(requestUri));
}
// Unbuffered by default
public Task<Stream> GetStreamAsync(Uri requestUri)
{
return FinishGetStreamAsync(GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead));
}
private async Task<Stream> FinishGetStreamAsync(Task<HttpResponseMessage> getTask)
{
HttpResponseMessage response = await getTask.ConfigureAwait(false);
response.EnsureSuccessStatusCode();
HttpContent c = response.Content;
return c != null ?
(c.TryReadAsStream() ?? await c.ReadAsStreamAsync().ConfigureAwait(false)) :
Stream.Null;
}
#endregion Simple Get Overloads
#region REST Send Overloads
public Task<HttpResponseMessage> GetAsync(string requestUri)
{
return GetAsync(CreateUri(requestUri));
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri)
{
return GetAsync(requestUri, defaultCompletionOption);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption)
{
return GetAsync(CreateUri(requestUri), completionOption);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption)
{
return GetAsync(requestUri, completionOption, CancellationToken.None);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, CancellationToken cancellationToken)
{
return GetAsync(CreateUri(requestUri), cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, CancellationToken cancellationToken)
{
return GetAsync(requestUri, defaultCompletionOption, cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
return GetAsync(CreateUri(requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
return SendAsync(CreateRequestMessage(HttpMethod.Get, requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)
{
return PostAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content)
{
return PostAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PostAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content)
{
return PutAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content)
{
return PutAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PutAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = CreateRequestMessage(HttpMethod.Put, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> PatchAsync(string requestUri, HttpContent content)
{
return PatchAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PatchAsync(Uri requestUri, HttpContent content)
{
return PatchAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PatchAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PatchAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PatchAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = CreateRequestMessage(HttpMethod.Patch, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> DeleteAsync(string requestUri)
{
return DeleteAsync(CreateUri(requestUri));
}
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri)
{
return DeleteAsync(requestUri, CancellationToken.None);
}
public Task<HttpResponseMessage> DeleteAsync(string requestUri, CancellationToken cancellationToken)
{
return DeleteAsync(CreateUri(requestUri), cancellationToken);
}
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri, CancellationToken cancellationToken)
{
return SendAsync(CreateRequestMessage(HttpMethod.Delete, requestUri), cancellationToken);
}
#endregion REST Send Overloads
#region Advanced Send Overloads
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
{
return SendAsync(request, defaultCompletionOption, CancellationToken.None);
}
public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
return SendAsync(request, defaultCompletionOption, cancellationToken);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption)
{
return SendAsync(request, completionOption, CancellationToken.None);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
CheckDisposed();
CheckRequestMessage(request);
SetOperationStarted();
PrepareRequestMessage(request);
// PrepareRequestMessage will resolve the request address against the base address.
// We need a CancellationTokenSource to use with the request. We always have the global
// _pendingRequestsCts to use, plus we may have a token provided by the caller, and we may
// have a timeout. If we have a timeout or a caller-provided token, we need to create a new
// CTS (we can't, for example, timeout the pending requests CTS, as that could cancel other
// unrelated operations). Otherwise, we can use the pending requests CTS directly.
CancellationTokenSource cts;
bool disposeCts;
bool hasTimeout = _timeout != s_infiniteTimeout;
if (hasTimeout || cancellationToken.CanBeCanceled)
{
disposeCts = true;
cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _pendingRequestsCts.Token);
if (hasTimeout)
{
cts.CancelAfter(_timeout);
}
}
else
{
disposeCts = false;
cts = _pendingRequestsCts;
}
// Initiate the send.
Task<HttpResponseMessage> sendTask;
try
{
sendTask = base.SendAsync(request, cts.Token);
}
catch
{
HandleFinishSendAsyncCleanup(cts, disposeCts);
throw;
}
return completionOption == HttpCompletionOption.ResponseContentRead && !string.Equals(request.Method.Method, "HEAD", StringComparison.OrdinalIgnoreCase) ?
FinishSendAsyncBuffered(sendTask, request, cts, disposeCts) :
FinishSendAsyncUnbuffered(sendTask, request, cts, disposeCts);
}
private async Task<HttpResponseMessage> FinishSendAsyncBuffered(
Task<HttpResponseMessage> sendTask, HttpRequestMessage request, CancellationTokenSource cts, bool disposeCts)
{
HttpResponseMessage response = null;
try
{
// Wait for the send request to complete, getting back the response.
response = await sendTask.ConfigureAwait(false);
if (response == null)
{
throw new InvalidOperationException(SR.net_http_handler_noresponse);
}
// Buffer the response content if we've been asked to and we have a Content to buffer.
if (response.Content != null)
{
await response.Content.LoadIntoBufferAsync(_maxResponseContentBufferSize, cts.Token).ConfigureAwait(false);
}
if (NetEventSource.IsEnabled) NetEventSource.ClientSendCompleted(this, response, request);
return response;
}
catch (Exception e)
{
response?.Dispose();
HandleFinishSendAsyncError(e, cts);
throw;
}
finally
{
HandleFinishSendAsyncCleanup(cts, disposeCts);
}
}
private async Task<HttpResponseMessage> FinishSendAsyncUnbuffered(
Task<HttpResponseMessage> sendTask, HttpRequestMessage request, CancellationTokenSource cts, bool disposeCts)
{
try
{
HttpResponseMessage response = await sendTask.ConfigureAwait(false);
if (response == null)
{
throw new InvalidOperationException(SR.net_http_handler_noresponse);
}
if (NetEventSource.IsEnabled) NetEventSource.ClientSendCompleted(this, response, request);
return response;
}
catch (Exception e)
{
HandleFinishSendAsyncError(e, cts);
throw;
}
finally
{
HandleFinishSendAsyncCleanup(cts, disposeCts);
}
}
private void HandleFinishSendAsyncError(Exception e, CancellationTokenSource cts)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, e);
// If the cancellation token was canceled, we consider the exception to be caused by the
// cancellation (e.g. WebException when reading from canceled response stream).
if (cts.IsCancellationRequested && e is HttpRequestException)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, "Canceled");
throw new OperationCanceledException(cts.Token);
}
}
private void HandleFinishSendAsyncCleanup(CancellationTokenSource cts, bool disposeCts)
{
// Dispose of the CancellationTokenSource if it was created specially for this request
// rather than being used across multiple requests.
if (disposeCts)
{
cts.Dispose();
}
// This method used to also dispose of the request content, e.g.:
// request.Content?.Dispose();
// This has multiple problems:
// 1. It prevents code from reusing request content objects for subsequent requests,
// as disposing of the object likely invalidates it for further use.
// 2. It prevents the possibility of partial or full duplex communication, even if supported
// by the handler, as the request content may still be in use even if the response
// (or response headers) has been received.
// By changing this to not dispose of the request content, disposal may end up being
// left for the finalizer to handle, or the developer can explicitly dispose of the
// content when they're done with it. But it allows request content to be reused,
// and more importantly it enables handlers that allow receiving of the response before
// fully sending the request. Prior to this change, a handler like CurlHandler would
// fail trying to access certain sites, if the site sent its response before it had
// completely received the request: CurlHandler might then find that the request content
// was disposed of while it still needed to read from it.
}
public void CancelPendingRequests()
{
CheckDisposed();
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
// With every request we link this cancellation token source.
CancellationTokenSource currentCts = Interlocked.Exchange(ref _pendingRequestsCts,
new CancellationTokenSource());
currentCts.Cancel();
currentCts.Dispose();
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
#endregion Advanced Send Overloads
#endregion Public Send
#region IDisposable Members
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
// Cancel all pending requests (if any). Note that we don't call CancelPendingRequests() but cancel
// the CTS directly. The reason is that CancelPendingRequests() would cancel the current CTS and create
// a new CTS. We don't want a new CTS in this case.
_pendingRequestsCts.Cancel();
_pendingRequestsCts.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region Private Helpers
private void SetOperationStarted()
{
// This method flags the HttpClient instances as "active". I.e. we executed at least one request (or are
// in the process of doing so). This information is used to lock-down all property setters. Once a
// Send/SendAsync operation started, no property can be changed.
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
}
private static void CheckRequestMessage(HttpRequestMessage request)
{
if (!request.MarkAsSent())
{
throw new InvalidOperationException(SR.net_http_client_request_already_sent);
}
}
private void PrepareRequestMessage(HttpRequestMessage request)
{
Uri requestUri = null;
if ((request.RequestUri == null) && (_baseAddress == null))
{
throw new InvalidOperationException(SR.net_http_client_invalid_requesturi);
}
if (request.RequestUri == null)
{
requestUri = _baseAddress;
}
else
{
// If the request Uri is an absolute Uri, just use it. Otherwise try to combine it with the base Uri.
if (!request.RequestUri.IsAbsoluteUri)
{
if (_baseAddress == null)
{
throw new InvalidOperationException(SR.net_http_client_invalid_requesturi);
}
else
{
requestUri = new Uri(_baseAddress, request.RequestUri);
}
}
}
// We modified the original request Uri. Assign the new Uri to the request message.
if (requestUri != null)
{
request.RequestUri = requestUri;
}
// Add default headers
if (_defaultRequestHeaders != null)
{
request.Headers.AddHeaders(_defaultRequestHeaders);
}
}
private static void CheckBaseAddress(Uri baseAddress, string parameterName)
{
if (baseAddress == null)
{
return; // It's OK to not have a base address specified.
}
if (!baseAddress.IsAbsoluteUri)
{
throw new ArgumentException(SR.net_http_client_absolute_baseaddress_required, parameterName);
}
if (!HttpUtilities.IsHttpUri(baseAddress))
{
throw new ArgumentException(SR.net_http_client_http_baseaddress_required, parameterName);
}
}
private Uri CreateUri(string uri) =>
string.IsNullOrEmpty(uri) ? null : new Uri(uri, UriKind.RelativeOrAbsolute);
private HttpRequestMessage CreateRequestMessage(HttpMethod method, Uri uri) =>
new HttpRequestMessage(method, uri) { Version = _defaultRequestVersion };
#endregion Private Helpers
}
}