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
/
HttpClientHandlerTest.cs
3230 lines (2932 loc) · 162 KB
/
HttpClientHandlerTest.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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
// Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary
// to separately Dispose (or have a 'using' statement) for the handler.
public abstract class HttpClientHandlerTest : HttpClientTestBase
{
readonly ITestOutputHelper _output;
private const string ExpectedContent = "Test content";
private const string Username = "testuser";
private const string Password = "password";
private const string HttpDefaultPort = "80";
private readonly NetworkCredential _credential = new NetworkCredential(Username, Password);
public static readonly object[][] EchoServers = Configuration.Http.EchoServers;
public static readonly object[][] VerifyUploadServers = Configuration.Http.VerifyUploadServers;
public static readonly object[][] CompressedServers = Configuration.Http.CompressedServers;
public static readonly object[][] Http2Servers = Configuration.Http.Http2Servers;
public static readonly object[][] Http2NoPushServers = Configuration.Http.Http2NoPushServers;
public static readonly object[][] RedirectStatusCodes = {
new object[] { 300 },
new object[] { 301 },
new object[] { 302 },
new object[] { 303 },
new object[] { 307 },
new object[] { 308 }
};
public static readonly object[][] RedirectStatusCodesOldMethodsNewMethods = {
new object[] { 300, "GET", "GET" },
new object[] { 300, "POST", "GET" },
new object[] { 300, "HEAD", "HEAD" },
new object[] { 301, "GET", "GET" },
new object[] { 301, "POST", "GET" },
new object[] { 301, "HEAD", "HEAD" },
new object[] { 302, "GET", "GET" },
new object[] { 302, "POST", "GET" },
new object[] { 302, "HEAD", "HEAD" },
new object[] { 303, "GET", "GET" },
new object[] { 303, "POST", "GET" },
new object[] { 303, "HEAD", "HEAD" },
new object[] { 307, "GET", "GET" },
new object[] { 307, "POST", "POST" },
new object[] { 307, "HEAD", "HEAD" },
new object[] { 308, "GET", "GET" },
new object[] { 308, "POST", "POST" },
new object[] { 308, "HEAD", "HEAD" },
};
// Standard HTTP methods defined in RFC7231: http://tools.ietf.org/html/rfc7231#section-4.3
// "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE"
public static readonly IEnumerable<object[]> HttpMethods =
GetMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CUSTOM1");
public static readonly IEnumerable<object[]> HttpMethodsThatAllowContent =
GetMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "CUSTOM1");
public static readonly IEnumerable<object[]> HttpMethodsThatDontAllowContent =
GetMethods("HEAD", "TRACE");
private static bool IsWindows10Version1607OrGreater => PlatformDetection.IsWindows10Version1607OrGreater;
private static IEnumerable<object[]> GetMethods(params string[] methods)
{
foreach (string method in methods)
{
foreach (bool secure in new[] { true, false })
{
yield return new object[] { method, secure };
}
}
}
public HttpClientHandlerTest(ITestOutputHelper output)
{
_output = output;
if (PlatformDetection.IsFullFramework)
{
// On .NET Framework, the default limit for connections/server is very low (2).
// On .NET Core, the default limit is higher. Since these tests run in parallel,
// the limit needs to be increased to avoid timeouts when running the tests.
System.Net.ServicePointManager.DefaultConnectionLimit = int.MaxValue;
}
}
[Fact]
public void CookieContainer_SetNull_ThrowsArgumentNullException()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Throws<ArgumentNullException>(() => handler.CookieContainer = null);
}
}
[Fact]
public void Ctor_ExpectedDefaultPropertyValues_CommonPlatform()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
// Same as .NET Framework (Desktop).
Assert.Equal(DecompressionMethods.None, handler.AutomaticDecompression);
Assert.True(handler.AllowAutoRedirect);
Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions);
CookieContainer cookies = handler.CookieContainer;
Assert.NotNull(cookies);
Assert.Equal(0, cookies.Count);
Assert.Null(handler.Credentials);
Assert.Equal(50, handler.MaxAutomaticRedirections);
Assert.NotNull(handler.Properties);
Assert.Equal(null, handler.Proxy);
Assert.True(handler.SupportsAutomaticDecompression);
Assert.True(handler.UseCookies);
Assert.False(handler.UseDefaultCredentials);
Assert.True(handler.UseProxy);
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
[Fact]
public void Ctor_ExpectedDefaultPropertyValues_NotUapPlatform()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
// Same as .NET Framework (Desktop).
Assert.Equal(64, handler.MaxResponseHeadersLength);
Assert.False(handler.PreAuthenticate);
Assert.True(handler.SupportsProxy);
Assert.True(handler.SupportsRedirectConfiguration);
// Changes from .NET Framework (Desktop).
if (!PlatformDetection.IsFullFramework)
{
Assert.False(handler.CheckCertificateRevocationList);
Assert.Equal(0, handler.MaxRequestContentBufferSize);
Assert.Equal(SslProtocols.None, handler.SslProtocols);
}
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsUap))]
public void Ctor_ExpectedDefaultPropertyValues_UapPlatform()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.True(handler.CheckCertificateRevocationList);
Assert.Equal(0, handler.MaxRequestContentBufferSize);
Assert.Equal(-1, handler.MaxResponseHeadersLength);
Assert.True(handler.PreAuthenticate);
Assert.Equal(SslProtocols.None, handler.SslProtocols);
Assert.False(handler.SupportsProxy);
Assert.False(handler.SupportsRedirectConfiguration);
}
}
[Fact]
public void Credentials_SetGet_Roundtrips()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
var creds = new NetworkCredential("username", "password", "domain");
handler.Credentials = null;
Assert.Null(handler.Credentials);
handler.Credentials = creds;
Assert.Same(creds, handler.Credentials);
handler.Credentials = CredentialCache.DefaultCredentials;
Assert.Same(CredentialCache.DefaultCredentials, handler.Credentials);
}
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
public void MaxAutomaticRedirections_InvalidValue_Throws(int redirects)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Throws<ArgumentOutOfRangeException>(() => handler.MaxAutomaticRedirections = redirects);
}
}
[Theory]
[InlineData(-1)]
[InlineData((long)int.MaxValue + (long)1)]
public void MaxRequestContentBufferSize_SetInvalidValue_ThrowsArgumentOutOfRangeException(long value)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Throws<ArgumentOutOfRangeException>(() => handler.MaxRequestContentBufferSize = value);
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP will send default credentials based on other criteria.")]
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task UseDefaultCredentials_SetToFalseAndServerNeedsAuth_StatusCodeUnauthorized(bool useProxy)
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.UseProxy = useProxy;
handler.UseDefaultCredentials = false;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.NegotiateAuthUriForDefaultCreds(secure: false);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
[ActiveIssue(29802, TargetFrameworkMonikers.Uap)]
[OuterLoop("Uses external server")]
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task DefaultHeaders_SetCredentials_ClearedOnRedirect(int statusCode)
{
if (statusCode == 308 && (PlatformDetection.IsFullFramework || IsWinHttpHandler && PlatformDetection.WindowsVersion < 10))
{
// 308 redirects are not supported on old versions of WinHttp, or on .NET Framework.
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
string credentialString = _credential.UserName + ":" + _credential.Password;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentialString);
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure: false,
statusCode: statusCode,
destinationUri: Configuration.Http.RemoteEchoServer,
hops: 1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
string responseText = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.False(TestHelper.JsonMessageContainsKey(responseText, "Authorization"));
}
}
}
[Fact]
public void Properties_Get_CountIsZero()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
IDictionary<string, object> dict = handler.Properties;
Assert.Same(dict, handler.Properties);
Assert.Equal(0, dict.Count);
}
}
[Fact]
public void Properties_AddItemToDictionary_ItemPresent()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
IDictionary<string, object> dict = handler.Properties;
var item = new object();
dict.Add("item", item);
object value;
Assert.True(dict.TryGetValue("item", out value));
Assert.Equal(item, value);
}
}
[OuterLoop("Uses external servers")]
[Theory, MemberData(nameof(EchoServers))]
public async Task SendAsync_SimpleGet_Success(Uri remoteServer)
{
using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.GetAsync(remoteServer))
{
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
[OuterLoop("Uses external server")]
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task SendAsync_GetWithValidHostHeader_Success(bool withPort)
{
var m = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.SecureRemoteEchoServer);
m.Headers.Host = withPort ? Configuration.Http.SecureHost + ":123" : Configuration.Http.SecureHost;
using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.SendAsync(m))
{
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task SendAsync_GetWithInvalidHostHeader_ThrowsException()
{
if (PlatformDetection.IsNetCore && !UseSocketsHttpHandler)
{
// Only .NET Framework and SocketsHttpHandler use the Host header to influence the SSL auth.
return;
}
var m = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.SecureRemoteEchoServer);
m.Headers.Host = "hostheaderthatdoesnotmatch";
using (HttpClient client = CreateHttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(m));
}
}
[ActiveIssue(22158, TargetFrameworkMonikers.Uap)]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // TODO: make unconditional after #26813 and #26476 are fixed
public async Task GetAsync_IPv6LinkLocalAddressUri_Success()
{
using (HttpClient client = CreateHttpClient())
{
var options = new LoopbackServer.Options { Address = TestHelper.GetIPv6LinkLocalAddress() };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
_output.WriteLine(url.ToString());
await TestHelper.WhenAllCompletedOrAnyFailed(
server.AcceptConnectionSendResponseAndCloseAsync(),
client.GetAsync(url));
}, options);
}
}
[Theory]
[MemberData(nameof(GetAsync_IPBasedUri_Success_MemberData))]
public async Task GetAsync_IPBasedUri_Success(IPAddress address)
{
using (HttpClient client = CreateHttpClient())
{
var options = new LoopbackServer.Options { Address = address };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
_output.WriteLine(url.ToString());
await TestHelper.WhenAllCompletedOrAnyFailed(
server.AcceptConnectionSendResponseAndCloseAsync(),
client.GetAsync(url));
}, options);
}
}
public static IEnumerable<object[]> GetAsync_IPBasedUri_Success_MemberData()
{
foreach (var addr in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback })
{
if (addr != null)
{
yield return new object[] { addr };
}
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task SendAsync_MultipleRequestsReusingSameClient_Success()
{
using (HttpClient client = CreateHttpClient())
{
for (int i = 0; i < 3; i++)
{
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success()
{
using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer))
{
client.Dispose();
Assert.NotNull(response);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(responseContent, response.Content.Headers.ContentMD5, false, null);
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task SendAsync_Cancel_CancellationTokenPropagates()
{
var cts = new CancellationTokenSource();
cts.Cancel();
using (HttpClient client = CreateHttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.RemoteEchoServer);
Task t = client.SendAsync(request, cts.Token);
OperationCanceledException ex;
if (PlatformDetection.IsUap)
{
ex = await Assert.ThrowsAsync<OperationCanceledException>(() => t);
}
else
{
ex = await Assert.ThrowsAsync<TaskCanceledException>(() => t);
}
Assert.True(cts.Token.IsCancellationRequested, "cts token IsCancellationRequested");
if (!PlatformDetection.IsFullFramework)
{
// .NET Framework has bug where it doesn't propagate token information.
Assert.True(ex.CancellationToken.IsCancellationRequested, "exception token IsCancellationRequested");
}
}
}
[OuterLoop("Uses external servers")]
[Theory, MemberData(nameof(CompressedServers))]
public async Task GetAsync_SetAutomaticDecompression_ContentDecompressed(Uri server)
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage response = await client.GetAsync(server))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP HTTP stack doesn't support .Proxy property")]
[Theory]
[InlineData("[::1234]")]
[InlineData("[::1234]:8080")]
public async Task GetAsync_IPv6AddressInHostHeader_CorrectlyFormatted(string host)
{
string ipv6Address = "http://" + host;
bool connectionAccepted = false;
await LoopbackServer.CreateClientAndServerAsync(async proxyUri =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.Proxy = new WebProxy(proxyUri);
try { await client.GetAsync(ipv6Address); } catch { }
}
}, server => server.AcceptConnectionAsync(async connection =>
{
connectionAccepted = true;
List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync();
Assert.Contains($"Host: {host}", headers);
}));
Assert.True(connectionAccepted);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP HTTP stack doesn't support .Proxy property")]
[Theory]
[InlineData("1.2.3.4")]
[InlineData("1.2.3.4:8080")]
[InlineData("[::1234]")]
[InlineData("[::1234]:8080")]
public async Task ProxiedIPAddressRequest_NotDefaultPort_CorrectlyFormatted(string host)
{
string uri = "http://" + host;
bool connectionAccepted = false;
await LoopbackServer.CreateClientAndServerAsync(async proxyUri =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.Proxy = new WebProxy(proxyUri);
try { await client.GetAsync(uri); } catch { }
}
}, server => server.AcceptConnectionAsync(async connection =>
{
connectionAccepted = true;
List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync();
Assert.Contains($"GET {uri}/ HTTP/1.1", headers);
}));
Assert.True(connectionAccepted);
}
public static IEnumerable<object[]> DestinationHost_MemberData()
{
yield return new object[] { Configuration.Http.Host };
yield return new object[] { "1.2.3.4" };
yield return new object[] { "[::1234]" };
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP HTTP stack doesn't support .Proxy property")]
[Theory]
[OuterLoop("Uses external server")]
[MemberData(nameof(DestinationHost_MemberData))]
public async Task ProxiedRequest_DefaultPort_PortStrippedOffInUri(string host)
{
string addressUri = $"http://{host}:{HttpDefaultPort}/";
string expectedAddressUri = $"http://{host}/";
bool connectionAccepted = false;
await LoopbackServer.CreateClientAndServerAsync(async proxyUri =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.Proxy = new WebProxy(proxyUri);
try { await client.GetAsync(addressUri); } catch { }
}
}, server => server.AcceptConnectionAsync(async connection =>
{
connectionAccepted = true;
List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync();
Assert.Contains($"GET {expectedAddressUri} HTTP/1.1", headers);
}));
Assert.True(connectionAccepted);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP HTTP stack doesn't support .Proxy property")]
[Fact]
[OuterLoop("Uses external server")]
public async Task ProxyTunnelRequest_PortSpecified_NotStrippedOffInUri()
{
// Https proxy request will use CONNECT tunnel, even the default 443 port is specified, it will not be stripped off.
string requestTarget = $"{Configuration.Http.SecureHost}:443";
string addressUri = $"https://{requestTarget}/";
bool connectionAccepted = false;
await LoopbackServer.CreateClientAndServerAsync(async proxyUri =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.Proxy = new WebProxy(proxyUri);
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
try { await client.GetAsync(addressUri); } catch { }
}
}, server => server.AcceptConnectionAsync(async connection =>
{
connectionAccepted = true;
List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync();
Assert.Contains($"CONNECT {requestTarget} HTTP/1.1", headers);
}));
Assert.True(connectionAccepted);
}
public static IEnumerable<object[]> SecureAndNonSecure_IPBasedUri_MemberData() =>
from address in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback }
from useSsl in new[] { true, false }
select new object[] { address, useSsl };
[ActiveIssue(30056, TargetFrameworkMonikers.Uap)]
[Theory]
[MemberData(nameof(SecureAndNonSecure_IPBasedUri_MemberData))]
public async Task GetAsync_SecureAndNonSecureIPBasedUri_CorrectlyFormatted(IPAddress address, bool useSsl)
{
var options = new LoopbackServer.Options { Address = address, UseSsl= useSsl };
bool connectionAccepted = false;
string host = "";
await LoopbackServer.CreateClientAndServerAsync(async url =>
{
host = $"{url.Host}:{url.Port}";
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
if (useSsl)
{
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
}
try { await client.GetAsync(url); } catch { }
}
}, server => server.AcceptConnectionAsync(async connection =>
{
connectionAccepted = true;
List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync();
Assert.Contains($"Host: {host}", headers);
}), options);
Assert.True(connectionAccepted);
}
[OuterLoop("Uses external server")]
[Theory, MemberData(nameof(CompressedServers))]
public async Task GetAsync_SetAutomaticDecompression_HeadersRemoved(Uri server)
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(server, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.False(response.Content.Headers.Contains("Content-Encoding"), "Content-Encoding unexpectedly found");
Assert.False(response.Content.Headers.Contains("Content-Length"), "Content-Length unexpectedly found");
}
}
[Theory]
#if netcoreapp
[InlineData(DecompressionMethods.Brotli, "br", "")]
[InlineData(DecompressionMethods.Brotli, "br", "br")]
[InlineData(DecompressionMethods.Brotli, "br", "gzip")]
[InlineData(DecompressionMethods.Brotli, "br", "gzip, deflate")]
#endif
[InlineData(DecompressionMethods.GZip, "gzip", "")]
[InlineData(DecompressionMethods.Deflate, "deflate", "")]
[InlineData(DecompressionMethods.GZip | DecompressionMethods.Deflate, "gzip, deflate", "")]
[InlineData(DecompressionMethods.GZip, "gzip", "gzip")]
[InlineData(DecompressionMethods.Deflate, "deflate", "deflate")]
[InlineData(DecompressionMethods.GZip, "gzip", "deflate")]
[InlineData(DecompressionMethods.GZip, "gzip", "br")]
[InlineData(DecompressionMethods.Deflate, "deflate", "gzip")]
[InlineData(DecompressionMethods.Deflate, "deflate", "br")]
[InlineData(DecompressionMethods.GZip | DecompressionMethods.Deflate, "gzip, deflate", "gzip, deflate")]
public async Task GetAsync_SetAutomaticDecompression_AcceptEncodingHeaderSentWithNoDuplicates(
DecompressionMethods methods,
string encodings,
string manualAcceptEncodingHeaderValues)
{
if (IsCurlHandler)
{
// Skip these tests on CurlHandler, dotnet/corefx #29905.
return;
}
if (!UseSocketsHttpHandler &&
(encodings.Contains("br") || manualAcceptEncodingHeaderValues.Contains("br")))
{
// Brotli encoding only supported on SocketsHttpHandler.
return;
}
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.AutomaticDecompression = methods;
using (var client = new HttpClient(handler))
{
if (!string.IsNullOrEmpty(manualAcceptEncodingHeaderValues))
{
client.DefaultRequestHeaders.Add("Accept-Encoding", manualAcceptEncodingHeaderValues);
}
Task<HttpResponseMessage> clientTask = client.GetAsync(url);
Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync();
await TaskTimeoutExtensions.WhenAllOrAnyFailed(new Task[] { clientTask, serverTask });
List<string> requestLines = await serverTask;
string requestLinesString = string.Join("\r\n", requestLines);
_output.WriteLine(requestLinesString);
Assert.InRange(Regex.Matches(requestLinesString, "Accept-Encoding").Count, 1, 1);
Assert.InRange(Regex.Matches(requestLinesString, encodings).Count, 1, 1);
if (!string.IsNullOrEmpty(manualAcceptEncodingHeaderValues))
{
Assert.InRange(Regex.Matches(requestLinesString, manualAcceptEncodingHeaderValues).Count, 1, 1);
}
using (HttpResponseMessage response = await clientTask)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
});
}
[OuterLoop("Uses external server")]
[Fact]
public async Task GetAsync_ServerNeedsBasicAuthAndSetDefaultCredentials_StatusCodeUnauthorized()
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Credentials = CredentialCache.DefaultCredentials;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: Username, password: Password);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task GetAsync_ServerNeedsAuthAndSetCredential_StatusCodeOK()
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Credentials = _credential;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: Username, password: Password);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[OuterLoop("Uses external server")]
[Fact]
public void GetAsync_ServerNeedsAuthAndNoCredential_StatusCodeUnauthorized()
{
// UAP HTTP stack caches connections per-process. This causes interference when these tests run in
// the same process as the other tests. Each test needs to be isolated to its own process.
// See dicussion: https://github.com/dotnet/corefx/issues/21945
RemoteInvoke(async useSocketsHttpHandlerString =>
{
using (var client = CreateHttpClient(useSocketsHttpHandlerString))
{
Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: Username, password: Password);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
return SuccessExitCode;
}
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[Theory]
[InlineData("WWW-Authenticate: CustomAuth\r\n")]
[InlineData("")] // RFC7235 requires servers to send this header with 401 but some servers don't.
public async Task GetAsync_ServerNeedsNonStandardAuthAndSetCredential_StatusCodeUnauthorized(string authHeaders)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Credentials = new NetworkCredential("unused", "unused");
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.Unauthorized);
await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask);
using (HttpResponseMessage response = await getResponseTask)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
});
}
[OuterLoop("Uses external server")]
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_AllowAutoRedirectFalse_RedirectFromHttpToHttp_StatusCodeRedirect(int statusCode)
{
if (statusCode == 308 && (PlatformDetection.IsFullFramework || IsWinHttpHandler && PlatformDetection.WindowsVersion < 10))
{
// 308 redirects are not supported on old versions of WinHttp, or on .NET Framework.
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = false;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure: false,
statusCode: statusCode,
destinationUri: Configuration.Http.RemoteEchoServer,
hops: 1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(statusCode, (int)response.StatusCode);
Assert.Equal(uri, response.RequestMessage.RequestUri);
}
}
}
[Theory, MemberData(nameof(RedirectStatusCodesOldMethodsNewMethods))]
public async Task AllowAutoRedirect_True_ValidateNewMethodUsedOnRedirection(
int statusCode, string oldMethod, string newMethod)
{
if (IsCurlHandler && statusCode == 300 && oldMethod == "POST")
{
// Known behavior: curl does not change method to "GET"
// https://github.com/dotnet/corefx/issues/26434
newMethod = "POST";
}
if (statusCode == 308 && (PlatformDetection.IsFullFramework || IsWinHttpHandler && PlatformDetection.WindowsVersion < 10))
{
// 308 redirects are not supported on old versions of WinHttp, or on .NET Framework.
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (origServer, origUrl) =>
{
var request = new HttpRequestMessage(new HttpMethod(oldMethod), origUrl);
Task<HttpResponseMessage> getResponseTask = client.SendAsync(request);
await LoopbackServer.CreateServerAsync(async (redirServer, redirUrl) =>
{
// Original URL will redirect to a different URL
Task<List<string>> serverTask = origServer.AcceptConnectionSendResponseAndCloseAsync((HttpStatusCode)statusCode, $"Location: {redirUrl}\r\n");
await Task.WhenAny(getResponseTask, serverTask);
Assert.False(getResponseTask.IsCompleted, $"{getResponseTask.Status}: {getResponseTask.Exception}");
await serverTask;
// Redirected URL answers with success
serverTask = redirServer.AcceptConnectionSendResponseAndCloseAsync();
await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask);
List<string> receivedRequest = await serverTask;
string[] statusLineParts = receivedRequest[0].Split(' ');
using (HttpResponseMessage response = await getResponseTask)
{
Assert.Equal(200, (int)response.StatusCode);
Assert.Equal(newMethod, statusLineParts[0]);
}
});
});
}
}
[ActiveIssue(30063, TargetFrameworkMonikers.Uap)] // fails due to TE header
[Theory]
[InlineData(300)]
[InlineData(301)]
[InlineData(302)]
[InlineData(303)]
public async Task AllowAutoRedirect_True_PostToGetDoesNotSendTE(int statusCode)
{
if (IsCurlHandler && statusCode == 300)
{
// ISSUE #26434:
// CurlHandler doesn't change POST to GET for 300 response (see above test).
return;
}
if (IsWinHttpHandler)
{
// ISSUE #27440:
// This test occasionally fails on WinHttpHandler.
// Likely this is due to the way the loopback server is sending the response before reading the entire request.
// We should change the server behavior here.
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (origServer, origUrl) =>
{
var request = new HttpRequestMessage(HttpMethod.Post, origUrl);
request.Content = new StringContent(ExpectedContent);
request.Headers.TransferEncodingChunked = true;
Task<HttpResponseMessage> getResponseTask = client.SendAsync(request);
await LoopbackServer.CreateServerAsync(async (redirServer, redirUrl) =>
{
// Original URL will redirect to a different URL
Task serverTask = origServer.AcceptConnectionAsync(async connection =>
{
// Send Connection: close so the client will close connection after request is sent,
// meaning we can just read to the end to get the content
await connection.ReadRequestHeaderAndSendResponseAsync((HttpStatusCode)statusCode, $"Location: {redirUrl}\r\nConnection: close\r\n");
connection.Socket.Shutdown(SocketShutdown.Send);
await connection.Reader.ReadToEndAsync();
});
await Task.WhenAny(getResponseTask, serverTask);
Assert.False(getResponseTask.IsCompleted, $"{getResponseTask.Status}: {getResponseTask.Exception}");
await serverTask;
// Redirected URL answers with success
List<string> receivedRequest = null;
string receivedContent = null;
Task serverTask2 = redirServer.AcceptConnectionAsync(async connection =>
{
// Send Connection: close so the client will close connection after request is sent,
// meaning we can just read to the end to get the content
receivedRequest = await connection.ReadRequestHeaderAndSendResponseAsync(additionalHeaders: "Connection: close\r\n");
connection.Socket.Shutdown(SocketShutdown.Send);
receivedContent = await connection.Reader.ReadToEndAsync();
});
await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask2);
string[] statusLineParts = receivedRequest[0].Split(' ');
Assert.Equal("GET", statusLineParts[0]);
Assert.DoesNotContain(receivedRequest, line => line.StartsWith("Transfer-Encoding"));
Assert.DoesNotContain(receivedRequest, line => line.StartsWith("Content-Length"));
using (HttpResponseMessage response = await getResponseTask)
{
Assert.Equal(200, (int)response.StatusCode);
}
});
});
}
}
[OuterLoop("Uses external server")]
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttp_StatusCodeOK(int statusCode)
{
if (statusCode == 308 && (PlatformDetection.IsFullFramework || IsWinHttpHandler && PlatformDetection.WindowsVersion < 10))
{
// 308 redirects are not supported on old versions of WinHttp, or on .NET Framework.
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure: false,
statusCode: statusCode,
destinationUri: Configuration.Http.RemoteEchoServer,
hops: 1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri);
}
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttps_StatusCodeOK()
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{