public async Task GetAsync_RedirectResponseHasCookie_CookieSentToFinalUri( CookieUsePolicy cookieUsePolicy, string cookieName, string cookieValue) { Uri uri = Configuration.Http.RedirectUriForDestinationUri(false, 302, Configuration.Http.RemoteEchoServer, 1); var handler = new WinHttpHandler(); handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; handler.CookieUsePolicy = cookieUsePolicy; if (cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer) { handler.CookieContainer = new CookieContainer(); } using (HttpClient client = new HttpClient(handler)) { client.DefaultRequestHeaders.Add( "X-SetCookie", string.Format("{0}={1};Path=/", cookieName, cookieValue)); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(JsonMessageContainsKeyValue(responseText, cookieName, cookieValue)); } } }
public void AutomaticRedirection_SetFalseAndGet_ValueIsFalse() { var handler = new WinHttpHandler(); handler.AutomaticRedirection = false; Assert.False(handler.AutomaticRedirection); }
public void Ctor_ExpectedDefaultPropertyValues() { var handler = new WinHttpHandler(); Assert.Equal(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, handler.SslProtocols); Assert.Equal(true, handler.AutomaticRedirection); Assert.Equal(50, handler.MaxAutomaticRedirections); Assert.Equal(DecompressionMethods.Deflate | DecompressionMethods.GZip, handler.AutomaticDecompression); Assert.Equal(CookieUsePolicy.UseInternalCookieStoreOnly, handler.CookieUsePolicy); Assert.Equal(null, handler.CookieContainer); Assert.Equal(null, handler.ServerCertificateValidationCallback); Assert.Equal(false, handler.CheckCertificateRevocationList); Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOption); X509Certificate2Collection certs = handler.ClientCertificates; Assert.True(certs.Count == 0); Assert.Equal(false, handler.PreAuthenticate); Assert.Equal(null, handler.ServerCredentials); Assert.Equal(WindowsProxyUsePolicy.UseWinHttpProxy, handler.WindowsProxyUsePolicy); Assert.Equal(CredentialCache.DefaultCredentials, handler.DefaultProxyCredentials); Assert.Equal(null, handler.Proxy); Assert.Equal(Int32.MaxValue, handler.MaxConnectionsPerServer); Assert.Equal(TimeSpan.FromSeconds(60), handler.ConnectTimeout); Assert.Equal(TimeSpan.FromSeconds(30), handler.SendTimeout); Assert.Equal(TimeSpan.FromSeconds(30), handler.ReceiveHeadersTimeout); Assert.Equal(TimeSpan.FromSeconds(30), handler.ReceiveDataTimeout); Assert.Equal(64 * 1024, handler.MaxResponseHeadersLength); Assert.Equal(64 * 1024, handler.MaxResponseDrainSize); }
public void CheckCertificateRevocationList_SetTrue_ExpectedWinHttpHandleSettings() { var handler = new WinHttpHandler(); SendRequestHelper(handler, delegate { handler.CheckCertificateRevocationList = true; }); Assert.True(APICallHistory.WinHttpOptionEnableSslRevocation.Value); }
private static HttpClient SetupHttp2Client(int maxConnectionsPerServer) { var winHttpHandler = new System.Net.Http.WinHttpHandler { ServerCertificateValidationCallback = (message, certificate2, arg3, arg4) => true, MaxConnectionsPerServer = maxConnectionsPerServer }; return(new HttpClient(winHttpHandler, true)); }
public async Task NoCallback_ValidCertificate_CallbackNotCalled() { var handler = new WinHttpHandler(); using (var client = new HttpClient(handler)) { HttpResponseMessage response = await client.GetAsync(HttpTestServers.SecureRemoteEchoServer); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.False(_validationCallbackHistory.WasCalled); } }
public void SendAsync_SlowServerRespondsAfterDefaultReceiveTimeout_ThrowsHttpRequestException() { var handler = new WinHttpHandler(); using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> t = client.GetAsync(SlowServer); AggregateException ag = Assert.Throws<AggregateException>(() => t.Wait()); Assert.IsType<HttpRequestException>(ag.InnerException); } }
public void SendAsync_SimpleGet_Success() { var handler = new WinHttpHandler(); var client = new HttpClient(handler); // TODO: This is a placeholder until GitHub Issue #2383 gets resolved. var response = client.GetAsync(HttpTestServers.RemoteGetServer).Result; Assert.Equal(HttpStatusCode.OK, response.StatusCode); var responseContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); _output.WriteLine(responseContent); }
public async Task UseCallback_NotSecureConnection_CallbackNotCalled() { var handler = new WinHttpHandler(); handler.ServerCertificateValidationCallback = CustomServerCertificateValidationCallback; using (var client = new HttpClient(handler)) { HttpResponseMessage response = await client.GetAsync(HttpTestServers.RemoteGetServer); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.False(_validationCallbackHistory.WasCalled); } }
public void AutomaticRedirection_SetFalse_ExpectedWinHttpHandleSettings() { var handler = new WinHttpHandler(); SendRequestHelper( handler, delegate { handler.AutomaticRedirection = false; }); Assert.Equal( Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER, APICallHistory.WinHttpOptionRedirectPolicy); }
public void AutomaticRedirection_SetTrue_ExpectedWinHttpHandleSettings() { var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.AutomaticRedirection = true; }); Assert.Equal( Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP, APICallHistory.WinHttpOptionRedirectPolicy); }
public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback() { var handler = new WinHttpHandler(); handler.ServerCertificateValidationCallback = CustomServerCertificateValidationCallback; using (var client = new HttpClient(handler)) { HttpResponseMessage response = await client.GetAsync(HttpTestServers.SecureRemoteEchoServer); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(_validationCallbackHistory.WasCalled); ConfirmValidCertificate(HttpTestServers.Host); } }
public async Task SendAsync_SlowServerAndCancel_ThrowsTaskCanceledException() { var handler = new WinHttpHandler(); using (var client = new HttpClient(handler)) { var cts = new CancellationTokenSource(); Task<HttpResponseMessage> t = client.GetAsync(SlowServer, cts.Token); await Task.Delay(500); cts.Cancel(); AggregateException ag = Assert.Throws<AggregateException>(() => t.Wait()); Assert.IsType<TaskCanceledException>(ag.InnerException); } }
public async Task UseCallback_RedirectandValidCertificate_ExpectedValuesDuringCallback() { Uri uri = Configuration.Http.RedirectUriForDestinationUri(true, 302, Configuration.Http.SecureRemoteEchoServer, 1); var handler = new WinHttpHandler(); handler.ServerCertificateValidationCallback = CustomServerCertificateValidationCallback; using (var client = new HttpClient(handler)) { HttpResponseMessage response = await client.GetAsync(uri); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(_validationCallbackHistory.WasCalled); ConfirmValidCertificate(Configuration.Http.Host); } }
public async Task CanReadAndWriteWithHttpsConnectionFilter() { RemoteCertificateValidationCallback validationCallback = (sender, cert, chain, sslPolicyErrors) => true; try { #if DNX451 var handler = new HttpClientHandler(); ServicePointManager.ServerCertificateValidationCallback += validationCallback; #else var handler = new WinHttpHandler(); handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; #endif var serverAddress = "https://*****:*****@"TestResources/testCert.pfx", "testPassword")}, new NoOpConnectionFilter()) }; using (var server = new TestServer(App, serviceContext, serverAddress)) { using (var client = new HttpClient(handler)) { var result = await client.PostAsync(serverAddress, new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("content", "Hello World?") })); Assert.Equal("content=Hello+World%3F", await result.Content.ReadAsStringAsync()); } } } finally { #if DNX451 ServicePointManager.ServerCertificateValidationCallback -= validationCallback; #endif } }
/// <summary> /// Sends an SMS message. /// </summary> /// <param name="message">SMS message.</param> /// <returns>Task.</returns> /// <exception cref="ArgumentNullException">If <paramref name="message"/> is <c>null</c>.</exception> public async Task SendSmsAsync(SmsMessage message) { if (message == null) throw new ArgumentNullException(nameof(message)); var url = ComposeUrl(message); #if NET45 var messageHandler = new WebRequestHandler(); messageHandler.ClientCertificates.Add(SmsConnectorConfiguration.Certificate); #else var messageHandler = new WinHttpHandler(); messageHandler.ClientCertificates.Add(SmsConnectorConfiguration.Certificate); #endif using (var client = new HttpClient(messageHandler)) { var response = await client.GetAsync(url).ConfigureAwait(false); await HandleErrorResponse(response).ConfigureAwait(false); } }
public void SendAsync_UseNoProxy_ExpectedWinHttpProxySettings() { var handler = new WinHttpHandler(); SendRequestHelper.Send(handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy; }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType); }
public async Task SendAsync_WinHttpOpenReturnsError_ExpectHttpRequestException() { var handler = new WinHttpHandler(); var client = new HttpClient(handler); var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint); TestControl.Fail.WinHttpOpen = true; Exception ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(request)); Assert.Equal(typeof(WinHttpException), ex.InnerException.GetType()); }
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectButPACFileNotDetectedOnNetwork_ExpectedWinHttpProxySettings() { TestControl.WinHttpAutomaticProxySupport = false; TestControl.PACFileNotDetectedOnNetwork = true; FakeRegistry.WinInetProxySettings.AutoDetect = true; var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.RequestProxySettings.AccessType); }
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectSettingAndManualSettingButPACFileNotFoundOnNetwork_ExpectedWinHttpProxySettings() { const string manualProxy = FakeProxy; TestControl.WinHttpAutomaticProxySupport = false; FakeRegistry.WinInetProxySettings.AutoDetect = true; FakeRegistry.WinInetProxySettings.Proxy = manualProxy; TestControl.PACFileNotDetectedOnNetwork = true; var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; }); // Both AutoDetect and manual proxy are specified. If AutoDetect fails to find // the PAC file on the network, then we should fall back to manual setting. Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType); Assert.Equal(manualProxy, APICallHistory.RequestProxySettings.Proxy); }
private static void OnRequestError(WinHttpRequestState state, Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult) { Debug.Assert(state != null, "OnRequestError: state is null"); if (NetEventSource.Log.IsEnabled()) { WinHttpTraceHelper.TraceAsyncError(state, asyncResult); } Exception innerException = WinHttpException.CreateExceptionUsingError(unchecked ((int)asyncResult.dwError), "WINHTTP_CALLBACK_STATUS_REQUEST_ERROR"); switch (unchecked ((uint)asyncResult.dwResult.ToInt32())) { case Interop.WinHttp.API_SEND_REQUEST: state.LifecycleAwaitable.SetException(innerException); break; case Interop.WinHttp.API_RECEIVE_RESPONSE: if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_RESEND_REQUEST) { state.RetryRequest = true; state.LifecycleAwaitable.SetResult(0); } else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED) { // WinHttp will automatically drop any client SSL certificates that we // have pre-set into the request handle including the NULL certificate // (which means we have no certs to send). For security reasons, we don't // allow the certificate to be re-applied. But we need to tell WinHttp // explicitly that we don't have any certificate to send. Debug.Assert(state.RequestHandle != null, "OnRequestError: state.RequestHandle is null"); WinHttpHandler.SetNoClientCertificate(state.RequestHandle); state.RetryRequest = true; state.LifecycleAwaitable.SetResult(0); } else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { state.LifecycleAwaitable.SetCanceled(state.CancellationToken); } else { state.LifecycleAwaitable.SetException(innerException); } break; case Interop.WinHttp.API_QUERY_DATA_AVAILABLE: if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Error(state, "QUERY_DATA_AVAILABLE - ERROR_WINHTTP_OPERATION_CANCELLED"); } state.LifecycleAwaitable.SetCanceled(); } else { state.LifecycleAwaitable.SetException( new IOException(SR.net_http_io_read, innerException)); } break; case Interop.WinHttp.API_READ_DATA: if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Error(state, "API_READ_DATA - ERROR_WINHTTP_OPERATION_CANCELLED"); } state.LifecycleAwaitable.SetCanceled(); } else { state.LifecycleAwaitable.SetException(new IOException(SR.net_http_io_read, innerException)); } break; case Interop.WinHttp.API_WRITE_DATA: Debug.Assert(state.TcsInternalWriteDataToRequestStream != null); if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Error(state, "API_WRITE_DATA - ERROR_WINHTTP_OPERATION_CANCELLED"); } state.TcsInternalWriteDataToRequestStream.TrySetCanceled(); } else { state.TcsInternalWriteDataToRequestStream.TrySetException( new IOException(SR.net_http_io_write, innerException)); } break; default: Debug.Fail( "OnRequestError: Result (" + asyncResult.dwResult + ") is not expected.", "Error code: " + asyncResult.dwError + " (" + innerException.Message + ")"); break; } }
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithMissingRegistrySettings_ExpectedWinHttpProxySettings() { TestControl.WinHttpAutomaticProxySupport = false; FakeRegistry.WinInetProxySettings.RegistryKeyMissing = true; var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType); Assert.Equal(false, APICallHistory.RequestProxySettings.AccessType.HasValue); }
public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsGZipCompressed_ExpectedResponse() { TestControl.WinHttpDecompressionSupport = false; var handler = new WinHttpHandler(); HttpResponseMessage response = SendRequestHelper.Send( handler, delegate { handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; TestServer.SetResponse(DecompressionMethods.GZip, TestServer.ExpectedResponseBody); }); Assert.Null(response.Content.Headers.ContentLength); string responseBody = await response.Content.ReadAsStringAsync(); Assert.Equal(0, response.Content.Headers.ContentEncoding.Count); Assert.Equal(TestServer.ExpectedResponseBody, responseBody); }
public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsNotCompressed_ExpectedResponse() { TestControl.WinHttpDecompressionSupport = false; var handler = new WinHttpHandler(); HttpResponseMessage response = SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; }); Assert.NotNull(response.Content.Headers.ContentLength); string responseBody = await response.Content.ReadAsStringAsync(); Assert.Equal(TestServer.ExpectedResponseBody, responseBody); }
public async Task SendAsync_PostNoContentObjectWithChunkedEncodingHeader_ExpectInvalidOperationException() { var handler = new WinHttpHandler(); var client = new HttpClient(handler); client.DefaultRequestHeaders.TransferEncodingChunked = true; TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody); var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint); await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request)); }
public async Task SendAsync_PostContentWithContentLengthAndChunkedEncodingHeaders_Success() { var handler = new WinHttpHandler(); var client = new HttpClient(handler); client.DefaultRequestHeaders.TransferEncodingChunked = true; TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody); var content = new StringContent(TestServer.ExpectedResponseBody); Assert.True(content.Headers.ContentLength.HasValue); var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint); request.Content = content; HttpResponseMessage response = await client.SendAsync(request); }
private static void OnRequestError(WinHttpRequestState state, Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult) { WinHttpTraceHelper.TraceAsyncError("OnRequestError", asyncResult); Debug.Assert(state != null, "OnRequestError: state is null"); Debug.Assert((unchecked ((int)asyncResult.dwError) != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER && unchecked ((int)asyncResult.dwError) != unchecked ((int)0x80090321)), // SEC_E_BUFFER_TOO_SMALL $"Unexpected async error in WinHttpRequestCallback: {unchecked((int)asyncResult.dwError)}, WinHttp API: {unchecked((uint)asyncResult.dwResult.ToInt32())}"); Exception innerException = WinHttpException.CreateExceptionUsingError(unchecked ((int)asyncResult.dwError)); switch (unchecked ((uint)asyncResult.dwResult.ToInt32())) { case Interop.WinHttp.API_SEND_REQUEST: state.LifecycleAwaitable.SetException(innerException); break; case Interop.WinHttp.API_RECEIVE_RESPONSE: if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_RESEND_REQUEST) { state.RetryRequest = true; state.LifecycleAwaitable.SetResult(0); } else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED) { // WinHttp will automatically drop any client SSL certificates that we // have pre-set into the request handle including the NULL certificate // (which means we have no certs to send). For security reasons, we don't // allow the certificate to be re-applied. But we need to tell WinHttp // explicitly that we don't have any certificate to send. Debug.Assert(state.RequestHandle != null, "OnRequestError: state.RequestHandle is null"); WinHttpHandler.SetNoClientCertificate(state.RequestHandle); state.RetryRequest = true; state.LifecycleAwaitable.SetResult(0); } else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { state.LifecycleAwaitable.SetCanceled(state.CancellationToken); } else { state.LifecycleAwaitable.SetException(innerException); } break; case Interop.WinHttp.API_QUERY_DATA_AVAILABLE: if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { // TODO: Issue #2165. We need to pass in the cancellation token from the // user's ReadAsync() call into the TrySetCanceled(). WinHttpTraceHelper.Trace("RequestCallback: QUERY_DATA_AVAILABLE - ERROR_WINHTTP_OPERATION_CANCELLED"); state.LifecycleAwaitable.SetCanceled(); } else { state.LifecycleAwaitable.SetException( new IOException(SR.net_http_io_read, innerException)); } break; case Interop.WinHttp.API_READ_DATA: if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { // TODO: Issue #2165. We need to pass in the cancellation token from the // user's ReadAsync() call into the TrySetCanceled(). WinHttpTraceHelper.Trace("RequestCallback: API_READ_DATA - ERROR_WINHTTP_OPERATION_CANCELLED"); state.LifecycleAwaitable.SetCanceled(); } else { state.LifecycleAwaitable.SetException(new IOException(SR.net_http_io_read, innerException)); } break; case Interop.WinHttp.API_WRITE_DATA: if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { // TODO: Issue #2165. We need to pass in the cancellation token from the // user's WriteAsync() call into the TrySetCanceled(). WinHttpTraceHelper.Trace("RequestCallback: API_WRITE_DATA - ERROR_WINHTTP_OPERATION_CANCELLED"); state.TcsInternalWriteDataToRequestStream.TrySetCanceled(); } else { state.TcsInternalWriteDataToRequestStream.TrySetException( new IOException(SR.net_http_io_write, innerException)); } break; default: Debug.Fail( "OnRequestError: Result (" + asyncResult.dwResult + ") is not expected.", "Error code: " + asyncResult.dwError + " (" + innerException.Message + ")"); break; } }
public async Task SendAsync_SlowPostRequestWithTimedCancellation_ExpectTaskCanceledException() { var handler = new WinHttpHandler(); TestControl.ResponseDelayTime = 500; CancellationTokenSource cts = new CancellationTokenSource(100); var client = new HttpClient(handler); var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint); var content = new StringContent(new String('a', 1000)); request.Content = content; await Assert.ThrowsAsync<TaskCanceledException>(() => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token)); }
public void SendAsync_UseCustomProxyWithBypass_ExpectedWinHttpProxySettings() { var handler = new WinHttpHandler(); var customProxy = new CustomProxy(true); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy; handler.Proxy = customProxy; }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.RequestProxySettings.AccessType); }
public void SendAsync_AutomaticProxySupportAndUseDefaultWebProxy_ExpectedWinHttpSessionProxySettings() { TestControl.WinHttpAutomaticProxySupport = true; var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy; handler.Proxy = new FakeDefaultWebProxy(); }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, APICallHistory.SessionProxySettings.AccessType); }
private static void OnRequestRedirect(WinHttpRequestState state, Uri redirectUri) { const string EmptyCookieHeader = "Cookie:"; Debug.Assert(state != null, "OnRequestRedirect: state is null"); Debug.Assert(redirectUri != null, "OnRequestRedirect: redirectUri is null"); Debug.Assert(state.TcsReceiveResponseHeaders != null, "TcsReceiveResponseHeaders is null"); Debug.Assert(!state.TcsReceiveResponseHeaders.Task.IsCompleted, "TcsReceiveResponseHeaders.Task is completed"); // If we're manually handling cookies, we need to reset them based on the new URI. if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer) { // Clear cookies. if (!Interop.WinHttp.WinHttpAddRequestHeaders( state.RequestHandle, EmptyCookieHeader, (uint)EmptyCookieHeader.Length, Interop.WinHttp.WINHTTP_ADDREQ_FLAG_REPLACE)) { int lastError = Marshal.GetLastWin32Error(); if (lastError != Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND) { throw WinHttpException.CreateExceptionUsingError(lastError); } } // Re-add cookies. The GetCookieHeader() method will return the correct set of // cookies based on the redirectUri. string cookieHeader = WinHttpHandler.GetCookieHeader(redirectUri, state.Handler.CookieContainer); if (!string.IsNullOrEmpty(cookieHeader)) { if (!Interop.WinHttp.WinHttpAddRequestHeaders( state.RequestHandle, cookieHeader, (uint)cookieHeader.Length, Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD)) { WinHttpException.ThrowExceptionUsingLastError(); } } } state.RequestMessage.RequestUri = redirectUri; // Redirection to a new uri may require a new connection through a potentially different proxy. // If so, we will need to respond to additional 407 proxy auth demands and re-attach any // proxy credentials. The ProcessResponse() method looks at the state.LastStatusCode // before attaching proxy credentials and marking the HTTP request to be re-submitted. // So we need to reset the LastStatusCode remembered. Otherwise, it will see additional 407 // responses as an indication that proxy auth failed and won't retry the HTTP request. if (state.LastStatusCode == HttpStatusCode.ProxyAuthenticationRequired) { state.LastStatusCode = 0; } // For security reasons, we drop the server credential if it is a // NetworkCredential. But we allow credentials in a CredentialCache // since they are specifically tied to URI's. if (!(state.ServerCredentials is CredentialCache)) { state.ServerCredentials = null; } }
public async Task SendAsync_RequestWithCanceledToken_ExpectTaskCanceledException() { var handler = new WinHttpHandler(); CancellationTokenSource cts = new CancellationTokenSource(); cts.Cancel(); var client = new HttpClient(handler); var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint); await Assert.ThrowsAsync<TaskCanceledException>(() => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token)); }
public async Task GetAsync_MultipleRequestsReusingSameClient_Success() { var handler = new WinHttpHandler(); var client = new HttpClient(handler); TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody); HttpResponseMessage response = await client.GetAsync(TestServer.FakeServerEndpoint); Assert.Equal(HttpStatusCode.OK, response.StatusCode); response = await client.GetAsync(TestServer.FakeServerEndpoint); Assert.Equal(HttpStatusCode.OK, response.StatusCode); response = await client.GetAsync(TestServer.FakeServerEndpoint); Assert.Equal(HttpStatusCode.OK, response.StatusCode); client.Dispose(); }
public void SendAsync_MultipleCallsWithoutDispose_NoHandleLeaksManuallyVerifiedUsingLogging() { WinHttpHandler handler; HttpResponseMessage response; for (int i = 0; i < 50; i++) { handler = new WinHttpHandler(); response = SendRequestHelper.Send(handler, () => { }); } }
private static void OnRequestError(WinHttpRequestState state, Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult) { WinHttpTraceHelper.TraceAsyncError("OnRequestError", asyncResult); Debug.Assert(state != null, "OnRequestError: state is null"); var innerException = WinHttpException.CreateExceptionUsingError((int)asyncResult.dwError).InitializeStackTrace(); switch ((uint)asyncResult.dwResult.ToInt32()) { case Interop.WinHttp.API_SEND_REQUEST: state.TcsSendRequest.TrySetException(innerException); break; case Interop.WinHttp.API_RECEIVE_RESPONSE: if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_RESEND_REQUEST) { state.RetryRequest = true; state.TcsReceiveResponseHeaders.TrySetResult(false); } else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED) { // WinHttp will automatically drop any client SSL certificates that we // have pre-set into the request handle including the NULL certificate // (which means we have no certs to send). For security reasons, we don't // allow the certificate to be re-applied. But we need to tell WinHttp // explicitly that we don't have any certificate to send. Debug.Assert(state.RequestHandle != null, "OnRequestError: state.RequestHandle is null"); WinHttpHandler.SetNoClientCertificate(state.RequestHandle); state.RetryRequest = true; state.TcsReceiveResponseHeaders.TrySetResult(false); } else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { state.TcsReceiveResponseHeaders.TrySetCanceled(state.CancellationToken); } else { state.TcsReceiveResponseHeaders.TrySetException(innerException); } break; case Interop.WinHttp.API_QUERY_DATA_AVAILABLE: if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { // TODO: Issue #2165. We need to pass in the cancellation token from the // user's ReadAsync() call into the TrySetCanceled(). Debug.WriteLine("RequestCallback: QUERY_DATA_AVAILABLE - ERROR_WINHTTP_OPERATION_CANCELLED"); state.TcsQueryDataAvailable.TrySetCanceled(); } else { state.TcsQueryDataAvailable.TrySetException( new IOException(SR.net_http_io_read, innerException)); } break; case Interop.WinHttp.API_READ_DATA: state.DisposeCtrReadFromResponseStream(); if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { // TODO: Issue #2165. We need to pass in the cancellation token from the // user's ReadAsync() call into the TrySetCanceled(). Debug.WriteLine("RequestCallback: API_READ_DATA - ERROR_WINHTTP_OPERATION_CANCELLED"); state.TcsReadFromResponseStream.TrySetCanceled(); } else { state.TcsReadFromResponseStream.TrySetException( new IOException(SR.net_http_io_read, innerException)); } break; case Interop.WinHttp.API_WRITE_DATA: if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { // TODO: Issue #2165. We need to pass in the cancellation token from the // user's WriteAsync() call into the TrySetCanceled(). Debug.WriteLine("RequestCallback: API_WRITE_DATA - ERROR_WINHTTP_OPERATION_CANCELLED"); state.TcsInternalWriteDataToRequestStream.TrySetCanceled(); } else { state.TcsInternalWriteDataToRequestStream.TrySetException( new IOException(SR.net_http_io_write, innerException)); } break; default: Debug.Fail( "OnRequestError: Result (" + asyncResult.dwResult + ") is not expected.", "Error code: " + asyncResult.dwError + " (" + innerException.Message + ")"); break; } }