3

The following code takes a target uri and gets its content as stream. Before the network call is made, it checks whether a proxy is required to access the target uri or not.

This works perfectly for .NET apps in full-framework (i.e. v4.8):

    var targetUri = new Uri("...");
    HttpClient client;

    // get the system default web proxy ...
    var proxyUri = WebRequest.DefaultWebProxy.GetProxy(targetUri);

    // ... and check whether it should be used or not
    var proxyAuthorityEqualsTargetAuthority = proxyUri?.Authority?.Equals(targetUri.Authority) == true;
    var proxyRequired = !proxyAuthorityEqualsTargetAuthority;

    if (proxyRequired)
    {
        var proxy = new WebProxy()
        {
            Address = proxyUri,
            BypassProxyOnLocal = false,
            UseDefaultCredentials = true
        };

        var httpClientHandler = new HttpClientHandler { Proxy = proxy };
        client = new HttpClient(handler: httpClientHandler, disposeHandler: true);
    }
    else
    {
        client = new HttpClient();
    }

    await client.GetStreamAsync(targetUri) ... 

However it does not work within a .NET Core app:

Accessing WebRequest.DefaultWebProxy.GetProxy(targetUri) will throw a PlatformNotSupportedException:

Operation is not supported on this platform.

So I tried this line instead which is supported by .NET Core as well:

    // deprecated: var proxyUri = new Uri(WebRequest.DefaultWebProxy.GetProxy(targetUri).AbsoluteUri);
    var proxyUri = new WebProxy().GetProxy(targetUri);

However, the returning proxyUri.Authority does always return the targetUri now (both, in .NET and .NET Core) instead of the address to the proxy server like WebRequest.DefaultWebProxy.GetProxy(targetUri) does in .NET.

This way, proxyAuthorityEqualsTargetAuthority is always true and therefore, proxyRequired is always false. Accessing the target uri directly throws a 407 (Proxy Authentication Required).

Does anyone know how to get the address of the default web proxy in .NET Core?

1 Answer 1

0

Okay, I don't know what I missed as I tried this weeks ago. I tried again and everything seems fine.

With CredentialCache.DefaultCredentials, this short code works with both: .NET and .NET Core.

    var targetUri = new Uri("...");

    var handler = new HttpClientHandler();
    handler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
    var client = new HttpClient(handler, disposeHandler: true);

    await client.GetStreamAsync(targetUri) ...
Sign up to request clarification or add additional context in comments.

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.