HttpWebRequest one proxy and one not

2019-04-29 08:20发布

问题:

How do i proxy my connections? i want 3 default HttpWebRequest objs that will not go through a proxy and another 3 that does. Do i do WebRequestObject.Proxy = myProxy; on objects i want to use a proxy on and do nothing on the 3 objs i do not? also the objects will initialize in an unknown order so i may have 2 not, 2 that is proxied, a 3rd that isnt and a final that is. Is it just simply writing .Proxy = myProxy?

回答1:

For requests that require a proxy, yes, that'll work fine:

request.Proxy = myProxy;

For requests that wish to bypass a proxy, use:

request.Proxy = System.Net.GlobalProxySelection.GetEmptyWebProxy;

If you want to use the IE's default proxy (or if you've set a default proxy in your app/web.config), simply don't set the proxy, or set it to null:

request.Proxy = null;

More about possible HttpWebRequest.Proxy values here and GetEmptyWebProxy here.



回答2:

System.Net.GlobalProxySelection.GetEmptyWebProxy is now deprecated.

I ended up with this situation

    private static void SetProxy(HttpWebRequest request)
    {
        if (AppConstants.UseProxyCredentials)
        {
            //request.Proxy = available in System.Net configuration settings
            request.Proxy.Credentials = Credentials.GetProxyCredentials();
        }
        else
        {
            request.Proxy = null;
            //request.Proxy.Credentials = n/a
        }
    }

With proxy details in web.config:

<system.net>
  <defaultProxy>
    <proxy
      autoDetect="False"
      bypassonlocal="True"
      scriptLocation="http://www.proxyscript..."
      proxyaddress="http://proxyurl..." />
  </defaultProxy>
</system.net>
<system.web>


回答3:

Yes you would create a new proxy object for each property on the request you want proxied and just leave it blank for the ones you done. For the ones you don't set they will use the default proxy values in the system.net configuration in your app.config.