Share via


Trying to obtain the proxy of a WebRequest throws an exception

The example of the WebRequest.Proxy property on MSDN shows this code:

  // Create a new request to the mentioned URL.
 WebRequest myWebRequest=WebRequest.Create("https://www.contoso.com");
 
 WebProxy myProxy=new WebProxy();
 
 // Obtain the Proxy Prperty of the Default browser. 
 myProxy=(WebProxy)myWebRequest.Proxy;
 
 

that throws the following exception on the last line of code when you run it:

"Unable to cast object of type 'WebProxyWrapper' to type 'System.Net.WebProxy'"

If you need to get the code to work without the exception, try this:

  Uri address = new Uri(https://www.bing.com);
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
 IWebProxy myProxy = request.Proxy;
 Uri proxyUri = myProxy.GetProxy(address);

Note, if there is no proxy set, the proxy returned in proxyUri will be equal to the URL address.  You can confirm this though a simple comparison of the URIs like this:

 if (address.Equals(proxyUri))

 I will link the MSDN article to this BLOG so that the documentation can be corrected.