public async Task GetAsync_SetCookieContainerAndCookieHeader_BothCookiesSent() { if (IsCurlHandler) { // Issue #26983 // CurlHandler ignores container cookies when custom Cookie header is set. return; } await LoopbackServer.CreateServerAsync(async (server, url) => { StandardSocketsHttpHandler handler = CreateSocketsHttpHandler(); handler.CookieContainer = CreateSingleCookieContainer(url); using (HttpClient client = new HttpClient(handler)) { HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url); requestMessage.Headers.Add("Cookie", s_customCookieHeaderValue); Task <HttpResponseMessage> getResponseTask = client.SendAsync(requestMessage); Task <List <string> > serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); List <string> requestLines = await serverTask; Assert.Equal(1, requestLines.Count(s => s.StartsWith("Cookie: "))); var cookies = requestLines.Single(s => s.StartsWith("Cookie: ")).Substring(8).Split(new string[] { "; " }, StringSplitOptions.None); Assert.Contains(s_expectedCookieHeaderValue, cookies); Assert.Contains(s_customCookieHeaderValue, cookies); Assert.Equal(2, cookies.Count()); } }); }
public void DefaultProtocols_MatchesExpected() { using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) { Assert.Equal(SslProtocols.None, handler.SslOptions.EnabledSslProtocols); } }
public async Task AutomaticOrManual_DoesntFailRegardlessOfWhetherClientCertsAreAvailable() { if (!BackendSupportsCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for SocketsHttpHandler { _output.WriteLine($"Skipping {nameof(Manual_CertificateSentMatchesCertificateReceived_Success)}()"); return; } using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) using (var client = new HttpClient(handler)) { handler.SslOptions.RemoteCertificateValidationCallback = SecurityHelper.AllowAllCertificates; await LoopbackServer.CreateServerAsync(async server => { Task clientTask = client.GetStringAsync(server.Uri); Task serverTask = server.AcceptConnectionAsync(async connection => { SslStream sslStream = Assert.IsType <SslStream>(connection.Stream); await connection.ReadRequestHeaderAndSendResponseAsync(); }); await new Task[] { clientTask, serverTask }.WhenAllOrAnyFailed(); }, new LoopbackServer.Options { UseSsl = true }); } }
public async Task HttpClientHandler_Authentication_Succeeds(string authenticateHeader, bool result) { if (PlatformDetection.IsWindowsNanoServer) { // TODO: #28065: Fix failing authentication test cases on different httpclienthandlers. return; } // Digest authentication does not work with domain credentials on CurlHandler. This is blocked by the behavior of LibCurl. NetworkCredential credentials = (IsCurlHandler && authenticateHeader.ToLowerInvariant().Contains("digest")) ? s_credentialsNoDomain : s_credentials; var options = new LoopbackServer.Options { Domain = Domain, Username = Username, Password = Password }; await LoopbackServer.CreateServerAsync(async (server, url) => { string serverAuthenticateHeader = $"WWW-Authenticate: {authenticateHeader}\r\n"; StandardSocketsHttpHandler handler = CreateSocketsHttpHandler(); Task serverTask = result ? server.AcceptConnectionPerformAuthenticationAndCloseAsync(serverAuthenticateHeader) : server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.Unauthorized, serverAuthenticateHeader); await TestHelper.WhenAllCompletedOrAnyFailedWithTimeout(TestHelper.PassingTestTimeoutMilliseconds, s_createAndValidateRequest(handler, url, result ? HttpStatusCode.OK : HttpStatusCode.Unauthorized, credentials), serverTask); }, options); }
public void Default_ExpectedValue() { using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) { Assert.Equal(int.MaxValue, handler.MaxConnectionsPerServer); } }
public void Set_InvalidValues_Throws(int invalidValue) { using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) { Assert.Throws <ArgumentOutOfRangeException>(() => handler.MaxConnectionsPerServer = invalidValue); } }
public async Task GetAsync_SetCookieContainerMultipleCookies_CookiesSent() { var cookies = new Cookie[] { new Cookie("hello", "world"), new Cookie("foo", "bar"), new Cookie("ABC", "123") }; await LoopbackServer.CreateServerAsync(async (server, url) => { StandardSocketsHttpHandler handler = CreateSocketsHttpHandler(); var cookieContainer = new CookieContainer(); foreach (Cookie c in cookies) { cookieContainer.Add(url, c); } handler.CookieContainer = cookieContainer; using (HttpClient client = new HttpClient(handler)) { Task <HttpResponseMessage> getResponseTask = client.GetAsync(url); Task <List <string> > serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); List <string> requestLines = await serverTask; string expectedHeader = "Cookie: " + string.Join("; ", cookies.Select(c => $"{c.Name}={c.Value}").ToArray()); Assert.Contains(expectedHeader, requestLines); Assert.Equal(1, requestLines.Count(s => s.StartsWith("Cookie:"))); } }); }
public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue, bool useCookies) { await LoopbackServer.CreateServerAsync(async (server, url) => { StandardSocketsHttpHandler handler = CreateSocketsHttpHandler(); handler.CookieContainer = CreateSingleCookieContainer(url, cookieName, cookieValue); handler.UseCookies = useCookies; using (HttpClient client = new HttpClient(handler)) { Task <HttpResponseMessage> getResponseTask = client.GetAsync(url); Task <List <string> > serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); List <string> requestLines = await serverTask; if (useCookies) { Assert.Contains($"Cookie: {GetCookieHeaderValue(cookieName, cookieValue)}", requestLines); Assert.Equal(1, requestLines.Count(s => s.StartsWith("Cookie:"))); } else { Assert.Equal(0, requestLines.Count(s => s.StartsWith("Cookie:"))); } } }); }
public async Task GetAsync_ReceiveInvalidSetCookieHeader_ValidCookiesAdded() { await LoopbackServer.CreateServerAsync(async (server, url) => { StandardSocketsHttpHandler handler = CreateSocketsHttpHandler(); using (HttpClient client = new HttpClient(handler)) { Task <HttpResponseMessage> getResponseTask = client.GetAsync(url); Task <List <string> > serverTask = server.AcceptConnectionSendResponseAndCloseAsync( HttpStatusCode.OK, $"Set-Cookie: A=1; Path=/;Expires=asdfsadgads\r\n" + // invalid Expires $"Set-Cookie: B=2; Path=/\r\n" + $"Set-Cookie: C=3; Path=/\r\n", s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(2, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[3]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); Assert.Contains(cookies, c => c.Name == "C" && c.Value == "3"); } }); }
public async Task SetDelegate_ConnectionSucceeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol) { using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) using (var client = new HttpClient(handler)) { handler.SslOptions.RemoteCertificateValidationCallback = SecurityHelper.AllowAllCertificates; // Refer issue: #22089 // When the server uses SslProtocols.Tls, on MacOS, SecureTransport ends up picking a cipher suite // for TLS1.2, even though server said it was only using TLS1.0. LibreSsl throws error that // wrong cipher is used for TLs1.0. if (requestOnlyThisProtocol || (PlatformDetection.IsMacOsHighSierraOrHigher && acceptedProtocol == SslProtocols.Tls)) { handler.SslOptions.EnabledSslProtocols = acceptedProtocol; } var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( server.AcceptConnectionSendResponseAndCloseAsync(), client.GetAsync(url)); }, options); } }
private async Task UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(string url, bool useSocketsHttpHandler, SslPolicyErrors expectedErrors) { if (!BackendSupportsCustomCertificateHandling) { Console.WriteLine($"Skipping {nameof(UseCallback_BadCertificate_ExpectedPolicyErrors)}({url}, {expectedErrors})"); return; } StandardSocketsHttpHandler handler = CreateSocketsHttpHandler(); using (var client = new HttpClient(handler)) { bool callbackCalled = false; handler.SslOptions.RemoteCertificateValidationCallback = (sender, cert, chain, errors) => { callbackCalled = true; Assert.NotNull(sender); Assert.NotNull(cert); Assert.NotNull(chain); Assert.Equal(expectedErrors, errors); return(true); }; using (HttpResponseMessage response = await client.GetAsync(url)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } Assert.True(callbackCalled); } }
public async Task GetAsync_NoSpecifiedProtocol_DefaultsToTls12() { if (!BackendSupportsSslConfiguration) { return; } using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) using (var client = new HttpClient(handler)) { handler.SslOptions.RemoteCertificateValidationCallback = SecurityHelper.AllowAllCertificates; var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = SslProtocols.Tls12 }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( client.GetAsync(url), server.AcceptConnectionAsync(async connection => { Assert.Equal(SslProtocols.Tls12, Assert.IsType <SslStream>(connection.Stream).SslProtocol); await connection.ReadRequestHeaderAndSendResponseAsync(); })); }, options); } }
[InlineData((HttpStatusCode)511)] // NetworkAuthenticationRequired public async Task PreAuthenticate_FirstRequestNoHeader_SecondRequestVariousStatusCodes_ThirdRequestPreauthenticates(HttpStatusCode statusCode) { const string AuthResponse = "WWW-Authenticate: Basic realm=\"hello\"\r\n"; await LoopbackServer.CreateClientAndServerAsync(async uri => { using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.ConnectionClose = true; // for simplicity of not needing to know every handler's pooling policy handler.PreAuthenticate = true; handler.Credentials = s_credentials; client.DefaultRequestHeaders.ExpectContinue = false; using (HttpResponseMessage resp = await client.GetAsync(uri)) { Assert.Equal(statusCode, resp.StatusCode); } Assert.Equal("hello world", await client.GetStringAsync(uri)); } }, async server => { List <string> headers = await server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.Unauthorized, AuthResponse); Assert.All(headers, header => Assert.DoesNotContain("Authorization", header)); headers = await server.AcceptConnectionSendResponseAndCloseAsync(statusCode); Assert.Contains(headers, header => header.Contains("Authorization")); headers = await server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.OK, content: "hello world"); Assert.Contains(headers, header => header.Contains("Authorization")); }); }
public async Task UseCallback_HaveNoCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_ProxyAuthenticationRequiredStatusCode() { if (!BackendSupportsCustomCertificateHandling) { return; } var options = new LoopbackProxyServer.Options { AuthenticationSchemes = AuthenticationSchemes.Basic, ConnectionCloseAfter407 = true }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) { StandardSocketsHttpHandler handler = CreateSocketsHttpHandler(); handler.Proxy = new WebProxy(proxyServer.Uri); handler.SslOptions.RemoteCertificateValidationCallback = delegate { return(true); }; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.PostAsync( Configuration.Http.SecureRemoteEchoServer, new StringContent("This is a test"))) { Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, response.StatusCode); } } }
public void InvalidValue_ThrowsException(int invalidValue) { using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) { AssertExtensions.Throws <ArgumentOutOfRangeException>("value", () => handler.MaxResponseHeadersLength = invalidValue); } }
public async Task GetAsync_AllowedSSLVersionDiffersFromServer_ThrowsException( SslProtocols allowedProtocol, SslProtocols acceptedProtocol) { if (!BackendSupportsSslConfiguration) { return; } using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) using (var client = new HttpClient(handler)) { handler.SslOptions.EnabledSslProtocols = allowedProtocol; handler.SslOptions.RemoteCertificateValidationCallback = SecurityHelper.AllowAllCertificates; var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol }; await LoopbackServer.CreateServerAsync(async (server, url) => { Task serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); await Assert.ThrowsAsync <HttpRequestException>(() => client.GetAsync(url)); try { await serverTask; } catch (Exception e) when(e is IOException || e is AuthenticationException) { // Some SSL implementations simply close or reset connection after protocol mismatch. // Newer OpenSSL sends Fatal Alert message before closing. return; } // We expect negotiation to fail so one or the other expected exception should be thrown. Assert.True(false, "Expected exception did not happen."); }, options); } }
public async Task GetAsync_ReceiveSetCookieHeader_CookieAdded(string cookieName, string cookieValue, bool useCookies) { await LoopbackServer.CreateServerAsync(async (server, url) => { StandardSocketsHttpHandler handler = CreateSocketsHttpHandler(); handler.UseCookies = useCookies; using (HttpClient client = new HttpClient(handler)) { Task <HttpResponseMessage> getResponseTask = client.GetAsync(url); Task <List <string> > serverTask = server.AcceptConnectionSendResponseAndCloseAsync( HttpStatusCode.OK, $"Set-Cookie: {GetCookieHeaderValue(cookieName, cookieValue)}\r\n", s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); if (useCookies) { Assert.Equal(1, collection.Count); Assert.Equal(cookieName, collection[0].Name); Assert.Equal(cookieValue, collection[0].Value); } else { Assert.Equal(0, collection.Count); } } }); }
public async Task GetAsync_AddMultipleCookieHeaders_CookiesSent() { await LoopbackServer.CreateServerAsync(async (server, url) => { StandardSocketsHttpHandler handler = CreateSocketsHttpHandler(); using (HttpClient client = new HttpClient(handler)) { HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url); requestMessage.Headers.Add("Cookie", "A=1"); requestMessage.Headers.Add("Cookie", "B=2"); requestMessage.Headers.Add("Cookie", "C=3"); Task <HttpResponseMessage> getResponseTask = client.SendAsync(requestMessage); Task <List <string> > serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); List <string> requestLines = await serverTask; Assert.Equal(1, requestLines.Count(s => s.StartsWith("Cookie: "))); // Multiple Cookie header values are treated as any other header values and are // concatenated using ", " as the separator. var cookieValues = requestLines.Single(s => s.StartsWith("Cookie: ")).Substring(8).Split(new string[] { ", " }, StringSplitOptions.None); Assert.Contains("A=1", cookieValues); Assert.Contains("B=2", cookieValues); Assert.Contains("C=3", cookieValues); Assert.Equal(3, cookieValues.Count()); } }); }
public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol) { if (!BackendSupportsSslConfiguration) { return; } #pragma warning disable 0618 if (UseSocketsHttpHandler || (IsCurlHandler && PlatformDetection.IsRedHatFamily6 && acceptedProtocol == SslProtocols.Ssl3)) { // TODO #26186: SocketsHttpHandler is failing on some OSes. return; } #pragma warning restore 0618 using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) using (var client = new HttpClient(handler)) { handler.SslOptions.RemoteCertificateValidationCallback = SecurityHelper.AllowAllCertificates; if (requestOnlyThisProtocol) { handler.SslOptions.EnabledSslProtocols = acceptedProtocol; } var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( server.AcceptConnectionSendResponseAndCloseAsync(), client.GetAsync(url)); }, options); } }
public void Ctor_ExpectedDefaultValues_NotUapPlatform() { using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) { Assert.Null(handler.SslOptions.RemoteCertificateValidationCallback); Assert.Equal(X509RevocationMode.NoCheck, handler.SslOptions.CertificateRevocationCheckMode); } }
public void ValidValue_SetGet_Roundtrips(int validValue) { using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) { handler.MaxResponseHeadersLength = validValue; Assert.Equal(validValue, handler.MaxResponseHeadersLength); } }
public void SetGetProtocols_Roundtrips(SslProtocols protocols) { using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) { handler.SslOptions.EnabledSslProtocols = protocols; Assert.Equal(protocols, handler.SslOptions.EnabledSslProtocols); } }
public async Task GetAsync_UnsupportedSSLVersion_Throws(SslProtocols sslProtocols, string url) { using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) using (HttpClient client = new HttpClient(handler)) { handler.SslOptions.EnabledSslProtocols = sslProtocols; await Assert.ThrowsAsync <HttpRequestException>(() => RemoteServerQuery.Run(() => client.GetAsync(url), remoteServerExceptionWrapper, url)); } }
public async Task Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache) { var options = new LoopbackProxyServer.Options { AuthenticationSchemes = creds != null ? AuthenticationSchemes.Basic : AuthenticationSchemes.None }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) { const string BasicAuth = "Basic"; if (wrapCredsInCache) { Assert.IsAssignableFrom <NetworkCredential>(creds); var cache = new CredentialCache(); cache.Add(proxyServer.Uri, BasicAuth, (NetworkCredential)creds); creds = cache; } using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) using (var client = new HttpClient(handler)) { handler.Proxy = new WebProxy(proxyServer.Uri) { Credentials = creds }; using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyResponseBody( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentMD5, false, null); if (options.AuthenticationSchemes != AuthenticationSchemes.None) { NetworkCredential nc = creds?.GetCredential(proxyServer.Uri, BasicAuth); Assert.NotNull(nc); string expectedAuth = string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" : $"{nc.Domain}\\{nc.UserName}:{nc.Password}"; _output.WriteLine($"expectedAuth={expectedAuth}"); string expectedAuthHash = Convert.ToBase64String(Encoding.UTF8.GetBytes(expectedAuth)); // Check last request to proxy server. CurlHandler will use pre-auth for Basic proxy auth, // so there might only be 1 request received by the proxy server. Other handlers won't use // pre-auth for proxy so there would be 2 requests. int requestCount = proxyServer.Requests.Count; _output.WriteLine($"proxyServer.Requests.Count={requestCount}"); Assert.Equal(BasicAuth, proxyServer.Requests[requestCount - 1].AuthorizationHeaderValueScheme); Assert.Equal(expectedAuthHash, proxyServer.Requests[requestCount - 1].AuthorizationHeaderValueToken); } } } } }
public async Task InvalidCertificateServers_CertificateValidationDisabled_Succeeds(string url) { using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) using (var client = new HttpClient(handler)) { handler.SslOptions.RemoteCertificateValidationCallback = SecurityHelper.AllowAllCertificates; (await client.GetAsync(url)).Dispose(); } }
public async Task GetAsync_SetCookieContainerAndMultipleCookieHeaders_BothCookiesSent() { if (IsCurlHandler) { // Issue #26983 // CurlHandler ignores container cookies when custom Cookie header is set. return; } await LoopbackServer.CreateServerAsync(async (server, url) => { StandardSocketsHttpHandler handler = CreateSocketsHttpHandler(); handler.CookieContainer = CreateSingleCookieContainer(url); using (HttpClient client = new HttpClient(handler)) { HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url); requestMessage.Headers.Add("Cookie", "A=1"); requestMessage.Headers.Add("Cookie", "B=2"); Task <HttpResponseMessage> getResponseTask = client.SendAsync(requestMessage); Task <List <string> > serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); List <string> requestLines = await serverTask; Assert.Equal(1, requestLines.Count(s => s.StartsWith("Cookie: "))); // Multiple Cookie header values are treated as any other header values and are // concatenated using ", " as the separator. The container cookie is concatenated to // one of these values using the "; " cookie separator. var cookieValues = requestLines.Single(s => s.StartsWith("Cookie: ")).Substring(8).Split(new string[] { ", " }, StringSplitOptions.None); Assert.Equal(2, cookieValues.Count()); // Find container cookie and remove it so we can validate the rest of the cookie header values bool sawContainerCookie = false; for (int i = 0; i < cookieValues.Length; i++) { if (cookieValues[i].Contains(';')) { Assert.False(sawContainerCookie); var cookies = cookieValues[i].Split(new string[] { "; " }, StringSplitOptions.None); Assert.Equal(2, cookies.Count()); Assert.Contains(s_expectedCookieHeaderValue, cookies); sawContainerCookie = true; cookieValues[i] = cookies.Where(c => c != s_expectedCookieHeaderValue).Single(); } } Assert.Contains("A=1", cookieValues); Assert.Contains("B=2", cookieValues); } }); }
public async Task SetAfterUse_Throws() { using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) using (var client = new HttpClient(handler)) { handler.MaxResponseHeadersLength = 1; (await client.GetStreamAsync(Configuration.Http.RemoteEchoServer)).Dispose(); Assert.Throws <InvalidOperationException>(() => handler.MaxResponseHeadersLength = 1); } }
public async Task GetAsync_MaxLimited_ConcurrentCallsStillSucceed(int maxConnections, int numRequests, bool secure) { using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) using (var client = new HttpClient(handler)) { handler.MaxConnectionsPerServer = maxConnections; await Task.WhenAll( from i in Enumerable.Range(0, numRequests) select client.GetAsync(secure ? Configuration.Http.RemoteEchoServer : Configuration.Http.SecureRemoteEchoServer)); } }
public async void HttpClientHandler_IncorrectCredentials_Fails(string authenticateHeader) { var options = new LoopbackServer.Options { Domain = Domain, Username = Username, Password = Password }; await LoopbackServer.CreateServerAsync(async (server, url) => { StandardSocketsHttpHandler handler = CreateSocketsHttpHandler(); Task serverTask = server.AcceptConnectionPerformAuthenticationAndCloseAsync(authenticateHeader); await TestHelper.WhenAllCompletedOrAnyFailed(s_createAndValidateRequest(handler, url, HttpStatusCode.Unauthorized, new NetworkCredential("wronguser", "wrongpassword")), serverTask); }, options); }
public async Task MaxConnectionsPerServer_WaitingConnectionsAreCancelable() { if (IsWinHttpHandler) { // Issue #27064: // Throws WinHttpException ("The server returned an invalid or unrecognized response") // while parsing headers. return; } using (StandardSocketsHttpHandler handler = CreateSocketsHttpHandler()) using (HttpClient client = new HttpClient(handler)) { handler.MaxConnectionsPerServer = 1; client.Timeout = Timeout.InfiniteTimeSpan; await LoopbackServer.CreateServerAsync(async (server, url) => { var serverAboutToBlock = new TaskCompletionSource <bool>(); var blockServerResponse = new TaskCompletionSource <bool>(); Task serverTask1 = server.AcceptConnectionAsync(async connection1 => { await connection1.ReadRequestHeaderAsync(); await connection1.Writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\n"); serverAboutToBlock.SetResult(true); await blockServerResponse.Task; await connection1.Writer.WriteAsync("Content-Length: 5\r\n\r\nhello"); }); Task get1 = client.GetAsync(url); await serverAboutToBlock.Task; var cts = new CancellationTokenSource(); Task get2 = ValidateClientCancellationAsync(() => client.GetAsync(url, cts.Token)); Task get3 = ValidateClientCancellationAsync(() => client.GetAsync(url, cts.Token)); Task get4 = client.GetAsync(url); cts.Cancel(); await get2; await get3; blockServerResponse.SetResult(true); await new[] { get1, serverTask1 }.WhenAllOrAnyFailed(); Task serverTask4 = server.AcceptConnectionSendResponseAndCloseAsync(); await new[] { get4, serverTask4 }.WhenAllOrAnyFailed(); }); } }