0

I use in my project many times the HttpWebRequest:

HttpWebRequest request = WebRequest.Create(requestedData) as HttpWebRequest;

Now, server's admin set a proxy for my connections. I'd like to add at any instance a code like this:

IWebProxy proxy = new WebProxy(Proxy, ProxyPort);
NetworkCredential nc = new NetworkCredential();

nc.UserName = ProxyLogin;
nc.Password = ProxyPassword;
request.Proxy = proxy;
request.Proxy.Credentials = nc;

without search for request on my project and add this code (as function).

Is there a fast way?

markzzz
  • 47,390
  • 120
  • 299
  • 507
  • `WebRequest.DefaultWebProxy`? – Damien_The_Unbeliever Dec 06 '13 at 11:32
  • ? I'm using `HttpWebRequest`.... – markzzz Dec 06 '13 at 11:45
  • But you said that you were using `WebRequest.Create(requestedData)` to *create* those `HttpWebRequest` objects, and `WebRequest` has a static property called `DefaultWebProxy`. – Damien_The_Unbeliever Dec 06 '13 at 11:47
  • Yes, but if So I need to replace all my connections with all code! I've Just asked if I can extend it in some way... – markzzz Dec 06 '13 at 11:53
  • 1
    You seem to be trying to make more work for yourself than you need. I'm saying you create one instance of the proxy object, assign it to `WebRequest.DefaultWebProxy`, and after that time, every call to `WebRequest.Create()` will already have that proxy assigned. There's no need to run code separately for each instance created. – Damien_The_Unbeliever Dec 06 '13 at 11:56
  • Can you give to me an example? I don't understand what do you mean... – markzzz Dec 06 '13 at 11:57

2 Answers2

3

During startup (e.g. at the start of Main for a console project, inside Global.asax's Application_Start for a web project, run the following code:

IWebProxy proxy = new WebProxy(Proxy, ProxyPort);
NetworkCredential nc = new NetworkCredential();

nc.UserName = ProxyLogin;
nc.Password = ProxyPassword;
proxy.Credentials = nc;
WebRequest.DefaultWebProxy = proxy;

After that above code has run, any code that looks like this:

HttpWebRequest request = WebRequest.Create(requestedData) as HttpWebRequest;

Will find that the Proxy property is already set correctly.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
1

You can also set the proxy for all HTTP requests from your application in the configuration with the <defaultProxy> element:

<configuration>
  <system.net>
    <defaultProxy>
      <proxy
        usesystemdefaults="true"
        proxyaddress="http://192.168.1.10:3128"
        bypassonlocal="true"
      />
      <bypasslist
        <add address="[a-z]+\.contoso\.com" />
      </bypasslist>
    </defaultProxy>
  </system.net>
</configuration>

Although that doesn't seem to work with authentication.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272