Search code examples
c#.netwpfhttppost

How do I fix my PostAsync request in C#, which doesn't take into account my proxy?


I am developing a WPF .dll with .NetFramework 4.6.1 and my services use http requests to reach my azure function server. I have created an interface to change the user settings and define the usage of a proxy but my requests don't take it into account.

This is the static class I use to setup my HttpClient and access it through getHttpClient() :

public static class ConnexionService
    {

        private static HttpClient httpClient;
        private static HttpClientHandler clientHandler = new HttpClientHandler();

        public static void SetupProxy()
        {
            try
            {
                if (Properties.Settings.Default.ProxyUsage)
                {
                    // Adresse et port du serveur proxy
                    Uri proxyAddress = new Uri($"http://{Properties.Settings.Default.ProxyAdress}:{Properties.Settings.Default.ProxyPort}");

                    // Création de l'objet proxy
                    WebProxy proxy = new WebProxy(Address: proxyAddress, BypassOnLocal: false)
                    {
                        UseDefaultCredentials = false,
                        Credentials = new NetworkCredential(
                           userName: Properties.Settings.Default.ProxyUser,
                           password: Properties.Settings.Default.ProxyPassword)

                    };
                    
                    // Création de l'objet HttpClientHandler et configuration pour utiliser le proxy
                    clientHandler = new HttpClientHandler()
                    {
                        UseProxy = true,
                        Proxy = proxy
                    };
                    httpClient = new HttpClient(handler: clientHandler, disposeHandler: true);
                }
                else {
                    httpClient = new HttpClient();
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        public static HttpClient getHttpClient()
        {
            SetupProxy();
            return httpClient;
        }
    }

And this is how I use it in one of my services :

public class AuthenticationService 
    {
        private readonly string Path = $"{Properties.Settings.Default.URL_API_DEV}/authentication";

        public async Task<Profile> LogIn(Profile profile)
        {
            var encryption = new Encryption();

            HttpContent content = new StringContent(encryption.Encrypt(JsonConvert.SerializeObject(profile)), Encoding.UTF8, "text/plain");
            try
            {
                using (var client = ConnexionService.getHttpClient())
                {
                    var endpoint = new Uri($"{Path.Trim()}/login");

                    var send = await client.PostAsync(endpoint, content);

                    if (!send.IsSuccessStatusCode)
                    {
                        Console.WriteLine($"Erreur : {send.StatusCode}");
                        return new Profile();
                    }

                    var encryptedResult = await send.Content.ReadAsStringAsync();
                    var decryptedResult = encryption.Decrypt(encryptedResult);
                    var response = JsonConvert.DeserializeObject<Profile>(decryptedResult);
                    return response;

                }

            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Erreur : {e.Message}");
                return new Profile();
            }
        }

Thank you for reading this far !


Solution

  • It now works, it seems that the problem was that I used using (var client = ConnexionService.getHttpClient()) which disposed my HttpClient. The working code is as follow :

    public class AuthenticationService 
    {
        private readonly string Path = $"{AzureService.GetEndPoint()}/authentication";
    
        public async Task<Profile> LogIn(Profile profile)
        {
            var encryption = new Encryption();
    
            HttpContent content = new StringContent(encryption.Encrypt(JsonConvert.SerializeObject(profile)), Encoding.UTF8, "text/plain");
            try
            {
                    var endpoint = new Uri($"{Path.Trim()}/login");
    
                    var send = await ConnexionService.getHttpClient().PostAsync(endpoint, content);
    
                    if (!send.IsSuccessStatusCode)
                    {
                        Console.WriteLine($"Erreur : {send.StatusCode}");
                        return new Profile();
                    }
    
                    var encryptedResult = await send.Content.ReadAsStringAsync();
                    var decryptedResult = encryption.Decrypt(encryptedResult);
                    var response = JsonConvert.DeserializeObject<Profile>(decryptedResult);
                    return response;
    
    
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Erreur : {e.Message}");
                return new Profile();
            }
        }
    }
    

    and

    public class ConnexionService {
    
        private static HttpClient httpClient =  null;
        private static HttpClientHandler clientHandler = new HttpClientHandler();
    
        public static HttpClient SetupProxy()
        {
            try
            {
                if (Properties.Settings.Default.ProxyUsage)
                {
                    // Adresse et port du serveur proxy
                    var proxyAddress = new Uri($"http://{Properties.Settings.Default.ProxyAdress}:{Properties.Settings.Default.ProxyPort}");
                    // Création de l'objet proxy
                    var proxy = new WebProxy(proxyAddress)
                    {
                        // Configuration des identifiants du proxy si nécessaire
                        Credentials = new NetworkCredential(Properties.Settings.Default.ProxyUser, new Encryption().Decrypt(Properties.Settings.Default.ProxyPassword))
                    };
    
                    // Création de l'objet HttpClientHandler et configuration pour utiliser le proxy
                    clientHandler = new HttpClientHandler()
                    {
                        Proxy = proxy,
                        UseProxy = true
                    };
                    httpClient = new HttpClient(clientHandler);
                    httpClient.DefaultRequestHeaders.Add(requestHeadersSTR, securityCodeSTR);
                }
                else {
                    httpClient = new HttpClient();
                    httpClient.DefaultRequestHeaders.Add(requestHeadersSTR, securityCodeSTR);
                    clientHandler = new HttpClientHandler()
                    {
                        UseProxy = false
                    };
                }
                return httpClient;
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
                return new HttpClient();
            }
        }
    
        public static HttpClient getHttpClient()
        {
            return SetupProxy();
        }
    }