HttpWebRequest WebExcepton: The remote server returned an error: (407) Proxy Authentication Required.

Problem

System.Net Tracing (see My Favorite System.Net Tracing File) revealed that we are getting the 407 error and the .NET framework is not retrying the request with Credentials. 

System.Net Error: 0 : [4811] Exception in the HttpWebRequest#33574938:: - The remote server returned an error: (407) Proxy Authentication Required. 

We can see in a Fiddler2 trace that Internet Explorer does submit the 407 credentials of the currently logged on user, but the HttpWebRequest does not even try.  We also see that for HTTP traffic there is no 407 in either request.  Only HTTPS traffic was requiring credentials for the proxy.

Resolution

By default the Proxy object does not supply the credentials of the Currently Logged on User.  You can fix this by:

1. Supply the credentials of the Currently Logged on User to the Proxy object similar to this:

Copy Code:

                    // Begin code change by jeff

                    // Obtain the 'Proxy' of the Default browser.

                    IWebProxy theProxy = aReq.Proxy;

                    // Print the Proxy Url to the console.

                    if (theProxy != null)

                    {

// Use the default credentials of the logged on user.

                        theProxy.Credentials = CredentialCache.DefaultCredentials;

                    }

                    // End code change by jeff

                    HttpWebResponse aResp = aReq.GetResponse() as HttpWebResponse;

2. Add this property to the <<application>>.exe.config or machine.config file:

Copy Code:

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