3

We use the following function to test internet connectivity every 5 seconds. But in some part of the world, this function always returns false. Now, the problem is we can set a proxy server in Windows to make this function return true, but we have to restart Windows after setting up the proxy server to make this happen. Is there any way to make the client.GetAsync() detect the proxy server settings instantly without restart Windows?

public static async Task<bool> TestInternetConnectivity()
{
    try
    {    
        var client = new HttpClient();
        var response = await client.GetAsync($"http://www.msftconnecttest.com/connecttest.txt");
        var result = await response.Content.ReadAsStringAsync();
    
        if (!string.Equals(result, "Microsoft Connect Test"))
           return false;
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

Image of proxy setting

5
  • 1
    Did you try: instead of new HttpClient() on each call, use the IHttpClientFactory ? Not sure if that fixes the problem, but it's an easy enough change to just give it a try. Commented Oct 29 at 10:23
  • 2
    Does restarting the app not help? Commented Oct 29 at 11:39
  • 2
    Why set proxy settings for Windows globally instead of setting a proxy for your HttpClient? Commented Oct 29 at 14:22
  • "every 5 seconds" Are you paying for those server resources? Commented Nov 4 at 0:42
  • @shingo, yes restart the application helps. I guess the system proxy server is saved in system variable and will only be get by the application at startup. Commented Nov 5 at 1:07

2 Answers 2

0

Due to the fact that the proxy settings are being changed exclusively for this process, I would recommend changing the code instead of global windows settings. An example of what you could do can be found in the solution to this question here.

Credit to ChaosPandion

public static bool CheckForInternetConnection(int timeoutMs = 10000, string url = null)
{
    try
    {
        url ??= CultureInfo.InstalledUICulture switch
        {
            { Name: var n } when n.StartsWith("fa") => // Iran
                "http://www.aparat.com",
            { Name: var n } when n.StartsWith("zh") => // China
                "http://www.baidu.com",
            _ =>
                "http://www.gstatic.com/generate_204",
        };

        var request = (HttpWebRequest)WebRequest.Create(url);
        request.KeepAlive = false;
        request.Timeout = timeoutMs;
        using (var response = (HttpWebResponse)request.GetResponse())
            return true;
    }
    catch
    {
        return false;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Since .net 9.0, the HttpClient's default proxy setting will be automatically updated when the related registry key is changed. (The premise is that the proxy is not set through HTTP(S)_PROXY environment variables)

Before that, you can call the Windows API WinHttpGetIEProxyConfigForCurrentUser to get the system proxy settings, and then update the default proxy of HttpClient:

if(WinHttpGetIEProxyConfigForCurrentUser(out var config) && !config.Proxy.IsNullOrEmpty())
    HttpClient.DefaultProxy = new WebProxy(config.Proxy);

[DllImport("Winhttp.dll")]
private static extern bool WinHttpGetIEProxyConfigForCurrentUser(out WINHTTP_CURRENT_USER_IE_PROXY_CONFIG config);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct WINHTTP_CURRENT_USER_IE_PROXY_CONFIG
{
    public bool AutoDetect;
    public string AutoConfigUrl;
    public string Proxy;
    public string ProxyBypass;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.