Beispiel #1
0
        public async Task SendAsync_HttpRequestMsgResponseHeadersRead_StatusCodeOK(Configuration.Http.RemoteServer remoteServer)
        {
            // Sync API supported only up to HTTP/1.1
            if (!TestAsync && remoteServer.HttpVersion.Major >= 2)
            {
                return;
            }

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, remoteServer.EchoUri)
            {
                Version = remoteServer.HttpVersion
            };

            using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
            {
                using (HttpResponseMessage response = await client.SendAsync(TestAsync, request, HttpCompletionOption.ResponseHeadersRead))
                {
                    string responseContent = await response.Content.ReadAsStringAsync();

                    _output.WriteLine(responseContent);
                    TestHelper.VerifyResponseBody(
                        responseContent,
                        response.Content.Headers.ContentMD5,
                        false,
                        null);
                }
            }
        }
Beispiel #2
0
        public async Task GetAsync_SetAutomaticDecompression_ContentDecompressed(Configuration.Http.RemoteServer remoteServer, Uri uri)
        {
            // Sync API supported only up to HTTP/1.1
            if (!TestAsync && remoteServer.HttpVersion.Major >= 2)
            {
                return;
            }

            HttpClientHandler handler = CreateHttpClientHandler();

            handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer, handler))
            {
                using (HttpResponseMessage response = await client.SendAsync(TestAsync, CreateRequest(HttpMethod.Get, uri, remoteServer.HttpVersion)))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    _output.WriteLine(responseContent);
                    TestHelper.VerifyResponseBody(
                        responseContent,
                        response.Content.Headers.ContentMD5,
                        false,
                        null);
                }
            }
        }
Beispiel #3
0
        public async Task SendAsync_SendRequestUsingMethodToEchoServerWithContent_Success(
            string method,
            bool secureServer)
        {
            using (var client = new HttpClient())
            {
                var request = new HttpRequestMessage(
                    new HttpMethod(method),
                    secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer);
                request.Content = new StringContent(ExpectedContent);
                using (HttpResponseMessage response = await client.SendAsync(request))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                    TestHelper.VerifyRequestMethod(response, method);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    _output.WriteLine(responseContent);
                    TestHelper.VerifyResponseBody(
                        responseContent,
                        response.Content.Headers.ContentMD5,
                        false,
                        ExpectedContent);
                }
            }
        }
        public async Task SendAsync_GetWithValidHostHeader_Success(bool withPort)
        {
            if (UseVersion == HttpVersion.Version30)
            {
                // External servers do not support HTTP3 currently.
                return;
            }

            var m = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.SecureRemoteEchoServer)
            {
                Version = UseVersion
            };

            m.Headers.Host = withPort ? Configuration.Http.SecureHost + ":443" : Configuration.Http.SecureHost;

            using (HttpClient client = CreateHttpClient())
                using (HttpResponseMessage response = await client.SendAsync(TestAsync, m))
                {
                    string responseContent = await response.Content.ReadAsStringAsync();

                    _output.WriteLine(responseContent);
                    TestHelper.VerifyResponseBody(
                        responseContent,
                        response.Content.Headers.ContentMD5,
                        false,
                        null);
                }
        }
Beispiel #5
0
        public void Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds)
        {
            int port;
            Task <LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
                out port,
                requireAuth: creds != null && creds != CredentialCache.DefaultCredentials,
                expectCreds: true);
            Uri proxyUrl = new Uri($"http://localhost:{port}");

            using (var handler = new HttpClientHandler()
            {
                Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds)
            })
                using (var client = new HttpClient(handler))
                {
                    Task <HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer);
                    Task <string> responseStringTask        = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
                    Task.WaitAll(proxyTask, responseTask, responseStringTask);

                    TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                    Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result);

                    NetworkCredential nc = creds != null?creds.GetCredential(proxyUrl, "Basic") : null;

                    string expectedAuth =
                        nc == null || nc == CredentialCache.DefaultCredentials ? null :
                        string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" :
                        $"{nc.Domain}\\{nc.UserName}:{nc.Password}";
                    Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue);
                }
        }
        public async Task UseCallback_HaveCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_Success()
        {
            var options = new LoopbackProxyServer.Options
            {
                AuthenticationSchemes   = AuthenticationSchemes.Basic,
                ConnectionCloseAfter407 = true
            };

            using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options))
            {
                HttpClientHandler handler = CreateHttpClientHandler();
                handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
                handler.Proxy = new WebProxy(proxyServer.Uri)
                {
                    Credentials = new NetworkCredential("rightusername", "rightpassword")
                };

                const string content = "This is a test";

                using (HttpClient client = CreateHttpClient(handler))
                    using (HttpResponseMessage response = await client.PostAsync(
                               Configuration.Http.SecureRemoteEchoServer,
                               new StringContent(content)))
                    {
                        string responseContent = await response.Content.ReadAsStringAsync();

                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                        TestHelper.VerifyResponseBody(
                            responseContent,
                            response.Content.Headers.ContentMD5,
                            false,
                            content);
                    }
            }
        }
Beispiel #7
0
        public async Task SendAsync_GetWithValidHostHeader_Success(bool withPort)
        {
            if (UseVersion == HttpVersion.Version30)
            {
                // External servers do not support HTTP3 currently.
                return;
            }
            if (PlatformDetection.LocalEchoServerIsAvailable && !withPort)
            {
                // we always have custom port with the local echo server, so we couldn't test without it
                return;
            }

            var m = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.SecureRemoteEchoServer)
            {
                Version = UseVersion
            };

            m.Headers.Host = !PlatformDetection.LocalEchoServerIsAvailable && withPort
                                ? Configuration.Http.SecureHost + ":" + Configuration.Http.SecurePort
                                : Configuration.Http.SecureHost;

            using (HttpClient client = CreateHttpClient())
                using (HttpResponseMessage response = await client.SendAsync(TestAsync, m))
                {
                    string responseContent = await response.Content.ReadAsStringAsync();

                    _output.WriteLine(responseContent);
                    TestHelper.VerifyResponseBody(
                        responseContent,
                        response.Content.Headers.ContentMD5,
                        false,
                        null);
                }
        }
Beispiel #8
0
        public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success(Configuration.Http.RemoteServer remoteServer)
        {
            using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
                using (HttpResponseMessage response = await client.GetAsync(remoteServer.EchoUri))
                {
                    client.Dispose();
                    Assert.NotNull(response);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    _output.WriteLine(responseContent);
                    TestHelper.VerifyResponseBody(responseContent, response.Content.Headers.ContentMD5, false, null);
                }
        }
        public async Task AuthProxy__ValidCreds_ProxySendsRequestToServer(
            AuthenticationSchemes proxyAuthScheme,
            bool secureServer,
            bool proxyClosesConnectionAfterFirst407Response)
        {
            if (PlatformDetection.IsWindowsNanoServer && IsWinHttpHandler && proxyAuthScheme == AuthenticationSchemes.Digest)
            {
                // WinHTTP doesn't support Digest very well and is disabled on Nano.
                return;
            }

            if (!PlatformDetection.IsWindows &&
                (proxyAuthScheme == AuthenticationSchemes.Negotiate || proxyAuthScheme == AuthenticationSchemes.Ntlm))
            {
                // CI machines don't have GSSAPI module installed and will fail with error from
                // System.Net.Security.NegotiateStreamPal.AcquireCredentialsHandle():
                //        "GSSAPI operation failed with error - An invalid status code was supplied
                //         Configuration file does not specify default realm)."
                return;
            }

            Uri serverUri = secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer;

            var options = new LoopbackProxyServer.Options
            {
                AuthenticationSchemes   = proxyAuthScheme,
                ConnectionCloseAfter407 = proxyClosesConnectionAfterFirst407Response
            };

            using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options))
            {
                using (HttpClientHandler handler = CreateHttpClientHandler())
                    using (HttpClient client = CreateHttpClient(handler))
                    {
                        handler.Proxy             = new WebProxy(proxyServer.Uri);
                        handler.Proxy.Credentials = new NetworkCredential("username", "password");
                        using (HttpResponseMessage response = await client.GetAsync(serverUri))
                        {
                            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                            TestHelper.VerifyResponseBody(
                                await response.Content.ReadAsStringAsync(),
                                response.Content.Headers.ContentMD5,
                                false,
                                null);
                        }
                    }
            }
        }
Beispiel #10
0
        private async Task PostHelper(
            Uri serverUri,
            string requestBody,
            HttpContent requestContent,
            bool useContentLengthUpload,
            bool useChunkedEncodingUpload)
        {
            using (HttpClient client = CreateHttpClient())
            {
                if (requestContent != null)
                {
                    if (useContentLengthUpload)
                    {
                        // Ensure that Content-Length is populated (see issue #27245)
                        requestContent.Headers.ContentLength = requestContent.Headers.ContentLength;
                    }
                    else
                    {
                        requestContent.Headers.ContentLength = null;
                    }
                }

                if (useChunkedEncodingUpload)
                {
                    client.DefaultRequestHeaders.TransferEncodingChunked = true;
                }

                using (HttpResponseMessage response = await client.PostAsync(serverUri, requestContent))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    _output.WriteLine(responseContent);

                    if (!useContentLengthUpload && !useChunkedEncodingUpload)
                    {
                        useChunkedEncodingUpload = true;
                    }

                    TestHelper.VerifyResponseBody(
                        responseContent,
                        response.Content.Headers.ContentMD5,
                        useChunkedEncodingUpload,
                        requestBody);
                }
            }
        }
Beispiel #11
0
        public async Task SendAsync_SimpleGet_Success(Uri remoteServer)
        {
            using (var client = new HttpClient())
            {
                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);
                }
            }
        }
        public async Task UseCallback_HaveCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_Success()
        {
            if (!BackendSupportsCustomCertificateHandling)
            {
                return;
            }

            if (IsWinHttpHandler && PlatformDetection.IsWindows7)
            {
                // Issue #27612
                return;
            }

            var options = new LoopbackProxyServer.Options
            {
                AuthenticationSchemes   = AuthenticationSchemes.Basic,
                ConnectionCloseAfter407 = true
            };

            using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options))
            {
                StandardSocketsHttpHandler handler = CreateSocketsHttpHandler();
                handler.SslOptions.RemoteCertificateValidationCallback = delegate { return(true); };
                handler.Proxy = new WebProxy(proxyServer.Uri)
                {
                    Credentials = new NetworkCredential("rightusername", "rightpassword")
                };

                const string content = "This is a test";

                using (var client = new HttpClient(handler))
                    using (HttpResponseMessage response = await client.PostAsync(
                               Configuration.Http.SecureRemoteEchoServer,
                               new StringContent(content)))
                    {
                        string responseContent = await response.Content.ReadAsStringAsync();

                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                        TestHelper.VerifyResponseBody(
                            responseContent,
                            response.Content.Headers.ContentMD5,
                            false,
                            content);
                    }
            }
        }
Beispiel #13
0
        public async Task UseCallback_HaveCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_Success()
        {
            if (!BackendSupportsCustomCertificateHandling)
            {
                return;
            }

            if (IsWinHttpHandler && PlatformDetection.IsWindows7)
            {
                // Issue #27612
                return;
            }

            const string content = "This is a test";

            int port;
            Task <LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
                out port,
                requireAuth: true,
                expectCreds: true);
            Uri proxyUrl = new Uri($"http://localhost:{port}");

            HttpClientHandler handler = CreateHttpClientHandler();

            handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, new NetworkCredential("rightusername", "rightpassword"));
            handler.ServerCertificateCustomValidationCallback = delegate { return(true); };
            using (var client = new HttpClient(handler))
            {
                HttpResponseMessage response = await client.PostAsync(
                    Configuration.Http.SecureRemoteEchoServer,
                    new StringContent(content));

                string responseContent = await response.Content.ReadAsStringAsync();

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                TestHelper.VerifyResponseBody(
                    responseContent,
                    response.Content.Headers.ContentMD5,
                    false,
                    content);
            }

            // Don't await proxyTask until the HttpClient is closed, otherwise it will wait for connection timeout.
            await proxyTask;
        }
Beispiel #14
0
        public async Task GetAsync_DefaultAutomaticDecompression_ContentDecompressed(Uri server)
        {
            using (var client = new HttpClient())
            {
                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);
                }
            }
        }
Beispiel #15
0
        public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success()
        {
            HttpResponseMessage response = null;

            using (var handler = new HttpClientHandler())
                using (var client = new HttpClient(handler))
                {
                    response = await client.GetAsync(HttpTestServers.SecureRemoteEchoServer);
                }
            Assert.NotNull(response);
            string responseContent = await response.Content.ReadAsStringAsync();

            _output.WriteLine(responseContent);
            TestHelper.VerifyResponseBody(
                responseContent,
                response.Content.Headers.ContentMD5,
                false,
                null);
        }
        public async Task SendAsync_GetWithValidHostHeader_Success(bool withPort)
        {
            var m = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.SecureRemoteEchoServer);

            m.Headers.Host = withPort ? Configuration.Http.SecureHost + ":443" : 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);
                }
        }
Beispiel #17
0
        public async Task SendAsync_HttpRequestMsgResponseHeadersRead_StatusCodeOK()
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, HttpTestServers.SecureRemoteEchoServer);

            using (var client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
                {
                    string responseContent = await response.Content.ReadAsStringAsync();

                    _output.WriteLine(responseContent);
                    TestHelper.VerifyResponseBody(
                        responseContent,
                        response.Content.Headers.ContentMD5,
                        false,
                        null);
                }
            }
        }
Beispiel #18
0
        public async Task PostAsync_CallMethod_NullContent(Configuration.Http.RemoteServer remoteServer)
        {
            using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
            {
                using (HttpResponseMessage response = await client.PostAsync(remoteServer.EchoUri, null))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);

                    string responseContent = await response.Content.ReadAsStringAsync();

                    _output.WriteLine(responseContent);
                    TestHelper.VerifyResponseBody(
                        responseContent,
                        response.Content.Headers.ContentMD5,
                        false,
                        string.Empty);
                }
            }
        }
        private async Task PostUsingAuthHelper(
            Uri serverUri,
            string requestBody,
            HttpContent requestContent,
            NetworkCredential credential,
            bool preAuthenticate)
        {
            StandardSocketsHttpHandler handler = CreateSocketsHttpHandler();

            handler.PreAuthenticate = preAuthenticate;
            handler.Credentials     = credential;
            using (var client = new HttpClient(handler))
            {
                // Send HEAD request to help bypass the 401 auth challenge for the latter POST assuming
                // that the authentication will be cached and re-used later when PreAuthenticate is true.
                var request = new HttpRequestMessage(HttpMethod.Head, serverUri);
                using (HttpResponseMessage response = await client.SendAsync(request))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                }

                // Now send POST request.
                request         = new HttpRequestMessage(HttpMethod.Post, serverUri);
                request.Content = requestContent;
                requestContent.Headers.ContentLength    = null;
                request.Headers.TransferEncodingChunked = true;

                using (HttpResponseMessage response = await client.SendAsync(request))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    _output.WriteLine(responseContent);

                    TestHelper.VerifyResponseBody(
                        responseContent,
                        response.Content.Headers.ContentMD5,
                        true,
                        requestBody);
                }
            }
        }
Beispiel #20
0
        public async Task PostAsync_CallMethod_EmptyContent(Uri remoteServer)
        {
            using (var client = new HttpClient())
            {
                var content = new StringContent(string.Empty);
                using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);

                    string responseContent = await response.Content.ReadAsStringAsync();

                    _output.WriteLine(responseContent);
                    TestHelper.VerifyResponseBody(
                        responseContent,
                        response.Content.Headers.ContentMD5,
                        false,
                        string.Empty);
                }
            }
        }