Default proxy in .net core 2.0

2020-08-11 05:45发布

问题:

I saw couple of questions asked about core 2.0 on how to make HttpClient to use default proxy configured on the system. But no where found right answer. Posting this question hoping someone who might have encountered this issue might have found the solution by now.

In .net framework versions I've used the following configuration in my web.config and it worked for me.

  <system.net>
    <defaultProxy useDefaultCredentials="true"></defaultProxy>
  </system.net>

But in .net core 2.0 where I've make a web request to external api from my company's intranet my code is failing with 407, proxy authentication required.

After little bit of research I am of the opinion that it is not possible to make your HttpClient to use default proxy settings configured via WPAD in IE. Can someone correct my understanding here?

On this page of https://github.com/dotnet/corefx/issues/7037

It is said as follows :

"The default for HttpClientHandler.UseProxy property is true. And the default value of HttpClientHandler.Proxy is NULL which means to use the default proxy."

But I don't observe this behavior.

Update:

I am finally able to call external web api by specifying the proxy server address and then making the HttpClient call. Still wondering how to use default proxy setup in IE.

 using (var handler = new HttpClientHandler {
                    Credentials = new System.Net.NetworkCredential(user, password, domain),

                    UseProxy = true,
                    Proxy = new System.Net.WebProxy(new Uri("http://xxxxxxx:8080"), true)                                       
                })
{

    handler.Proxy.Credentials = new NetworkCredential("xxxx", "yyyyy", "cccccc");                    
    using (var httpClient = new HttpClient(handler))
    {
        var request = new HttpRequestMessage()
        {
            RequestUri = new Uri(destinationUrl),
            Method = HttpMethod.Post
        };

        request.Content = new StringContent(requestXml, Encoding.UTF8, "text/xml");             

        HttpResponseMessage response = await httpClient.SendAsync(request);

        Task<Stream> streamTask = response.Content.ReadAsStreamAsync();
    }
}   

If any one interested in finding out how I was able to find out the proxy server was, I wrote the following code in .net 4.0 and found out the proxy used.

var proxy = WebRequest.GetSystemWebProxy();
var url = proxy.GetProxy(new Uri("http://google.com"));

Thanks

回答1:

I hope this is the answer you're looking for: Default Proxy issues #28780

If you simply want to use the default system proxy and need to pass default credentials to that proxy (because the proxy is an authenticated proxy) during HTTP requests, then do this:

var handler = new HttpClientHandler();
handler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
var client = new HttpClient(handler);