tags:

views:

5922

answers:

1

The following code works for me:

var webProxy = WebProxy.GetDefaultProxy();
webProxy.UseDefaultCredentials = true;
WebRequest.DefaultWebProxy = webProxy;

Unfortunately, WebProxy.GetDefaultProxy() is deprecated. What else should I be doing?

(using app.config to set the defaultProxy settings is not allowed in my deployment)

+10  A: 

From .NET 2.0 you shouldn't need to do this. If you do not explicitly set the Proxy property on a web request it uses the value of the static WebRequest.DefaultWebProxy. If you wanted to change the proxy being used by all subsequent WebRequests, you can set this static DefaultWebProxy property.

The default behaviour of WebRequest.DefaultWebProxy is to use the same underlying settings as used by Internet Explorer.

If you wanted to use different proxy settings to the current user then you would need to code

WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);

or

WebRequest.DefaultWebProxy = new WebProxy("http://proxyserver:80/",true);

You should also remember the object model for proxies includes the concept that the proxy can be different depending on the destination hostname. This can make things a bit confusing when debugging and checking the property of webRequest.Proxy. Call webRequest.Proxy.GetProxy(new Uri("http://google.com.au")) to see the actual details of the proxy server that would be used.

There seems to be some debate about whether you can set webRequest.Proxy or WebRequest.DefaultWebProxy = null to prevent the use of any proxy. This seems to work OK for me but you could set it to new DefaultProxy() with no parameters to get the required behaviour. Another thing to check is that if a proxy element exists in your applications config file, the .NET Framework will NOT use the proxy settings in Internet Explorer.

The MSDN Magazine article Take the Burden Off Users with Automatic Configuration in .NET gives further details of what is happening under the hood.

Martin Hollingsworth
+1 very good explication
Daok
I agree that it FEELS like I shouldn't need to do this, but I do. If I don't do this, I get a 407 failure on the default proxy authentication. If I DO this, then my client can get through the proxy.
Brian Genisio
Is it possibly that you have a <proxy> element in your .config file? If so get rid of it and try again.
Martin Hollingsworth
The setting in the config file was the only thing that got it to work... but I was just playing around with it. I don't have access to .config in my environment at all, so this isn't an option for me.
Brian Genisio