C# Connecting Through Proxy
Asked Answered
I

10

105

I work in a office which requires all connections to be made through a specific http proxy. I need to write a simple application to query some values from a webserver - it's easy if there were no proxy. How can I make the C# application proxy-aware? How can I make any sort of connection through a proxy?

Indicatory answered 21/12, 2009 at 9:3 Comment(0)
R
122

This is easily achieved either programmatically, in your code, or declaratively in either the web.config or the app.config.

You can programmatically create a proxy like so:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("[ultimate destination of your request]");
WebProxy myproxy = new WebProxy("[your proxy address]", [your proxy port number]);
myproxy.BypassProxyOnLocal = false;
request.Proxy = myproxy;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse) request.GetResponse();

You're basically assigning the WebProxy object to the request object's proxy property. This request will then use the proxy you define.

To achieve the same thing declaratively, you can do the following:

<system.net>
  <defaultProxy>
    <proxy
      proxyaddress="http://[your proxy address and port number]"
      bypassonlocal="false"
    />
  </defaultProxy>
</system.net>

within your web.config or app.config. This sets a default proxy that all http requests will use. Depending upon exactly what you need to achieve, you may or may not require some of the additional attributes of the defaultProxy / proxy element, so please refer to the documentation for those.

Resolvent answered 21/12, 2009 at 9:10 Comment(4)
in programatical example, you did not set the port, WHY?Heriberto
@Heriberto - No particular reason. That was merely an oversight as in that example, I'm using the constructor which takes the URL (as a string) and a boolean to determine if local addresses are bypassed. If you need a specific port number, it might be better to use the overloaded constructor that allows the URL (as a string) and the port number (as an Int32), then set the BypassProxyOnLocal property to True (if required) immediately afterwards.Resolvent
@Heriberto - I have edited my post to clarify this and to ensure that the programmatic and declarative examples are actually doing the same thing!Resolvent
great example. How to achieve the same for TcpClient ? I have used TcpClient to TEST some connection but now I want to make sure it works behind the proxy.Timorous
E
23

If you are using WebClient, it has a Proxy property you can use.

As other have mentioned, there are several ways to automate proxy setting detection/usage

Web.Config:

<system.net>
   <defaultProxy enabled="true" useDefaultCredentials="true">
     <proxy usesystemdefault="true" bypassonlocal="true" />
   </defaultProxy>
</system.net>

Use of the WebProxy class as described in this article.


You can also cofigure the proxy settings directly (config or code) and your app will then use those.

Web.Config:

<system.net>
  <defaultProxy>
    <proxy
      proxyaddress="http://[proxy address]:[proxy port]"
      bypassonlocal="false"
    />
  </defaultProxy>
</system.net>

Code:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
WebProxy myproxy = new WebProxy("[proxy address]:[proxy port]", false);
request.Proxy = myproxy;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Equerry answered 21/12, 2009 at 9:6 Comment(0)
I
7

If you want the app to use the system default proxy, add this to your Application.exe.config (where application.exe is the name of your application):

<system.net>
   <defaultProxy enabled="true" useDefaultCredentials="true">
   <proxy usesystemdefault="true" bypassonlocal="true" />
   </defaultProxy>
</system.net>

More details can be found on in the MSDN article on System.Net

Idioglossia answered 21/12, 2009 at 9:9 Comment(1)
Note: The: <system.net> section goes inside the <configuration> section or the exe.config file. This got the proxy stuff working in a simple console app I cooked up.Loewe
C
7

Try this code. Call it before making any http requests. The code will use the proxy from your Internet Explorer Settings - one thing though, I use proxy.Credentials = .... because my proxy server is an NTLM authenticated Internet Acceleration Server. Give it a whizz.

static void setProxy()
{
    WebProxy proxy = (WebProxy)WebProxy.GetDefaultProxy();
    if(proxy.Address != null)
    {
        proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
        WebRequest.DefaultWebProxy = new System.Net.WebProxy(proxy.Address, proxy.BypassProxyOnLocal, proxy.BypassList, proxy.Credentials);
    }
}
Chatham answered 10/5, 2011 at 21:25 Comment(1)
WebProxy.GetDefaultProxy is obsolete since Framework 4.5 and this method returns null. Better think before usingCredentialCache.DefaultNetworkCredentials. If you had put something in CredentialCache and your proxy require such credentials, then it should work. Otherwise it will not help.Liebig
H
7

This one-liner works for me:

WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;

CredentialCache.DefaultNetWorkCredentials is the proxy settings set in Internet Explorer.

WebRequest.DefaultWebProxy.Credentials is used for all internet connectivity in the application.

Heliacal answered 14/11, 2015 at 12:57 Comment(3)
"CredentialCache.DefaultNetWorkCredentials is the proxy settings set in Internet Explorer". Is this still the case? I can't find anywhere in Internet Options > Connections > LAN Settings to write a username and password.Mesolithic
From the docs: "For a client-side application, these are usually the Windows credentials (user name, password, and domain) of the user running the application."Heliacal
This answer may have aged a bit poorly, but I'm pretty sure it was true for 2015 windowsHeliacal
P
4

Foole's code worked perfectly for me, but in .NET 4.0, don't forget to check if Proxy is NULL, which means no proxy configured (outside corporate environment)

So here's the code that solved my problem with our corporate proxy

WebClient web = new WebClient();
if (web.Proxy != null)
    web.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
Pullen answered 23/11, 2012 at 12:52 Comment(0)
S
3

This code has worked for me:

WebClient wc = new WebClient();
wc.Proxy.Credentials = CredentialCache.DefaultCredentials;
Signpost answered 21/12, 2009 at 9:31 Comment(0)
G
0

Automatic proxy detection is a process by which a Web proxy server is identified by the system and used to send requests on behalf of the client. This feature is also known as Web Proxy Auto-Discovery (WPAD). When automatic proxy detection is enabled, the system attempts to locate a proxy configuration script that is responsible for returning the set of proxies that can be used for the request.

http://msdn.microsoft.com/en-us/library/fze2ytx2.aspx

Goldman answered 21/12, 2009 at 9:11 Comment(1)
How does this answer the question? How can the OP put this information to use?Lamplighter
L
0
            var getHtmlWeb = new HtmlWeb() { AutoDetectEncoding = false, OverrideEncoding = Encoding.GetEncoding("iso-8859-2") };

            WebProxy myproxy = new WebProxy("127.0.0.1:8888", false);
            NetworkCredential cred = (NetworkCredential)CredentialCache.DefaultCredentials;
            var document = getHtmlWeb.Load("URL", "GET", myproxy, cred);
Letishaletitia answered 16/5, 2015 at 17:40 Comment(1)
Its is preferable to write an explanation of your solution and not just post code. Can you edit in some text that would help the reader?Pierrepierrepont
D
0

I am going to use an example to add to the answers above.

I ran into proxy issues while trying to install packages via Web Platform Installer

That too uses a config file which is WebPlatformInstaller.exe.config

I tried the edits suggest in this IIS forum which is

<?xml version="1.0" encoding="utf-8" ?>
<configuration>  
  <system.net>    
     <defaultProxy enabled="True" useDefaultCredentials="True"/>      
   </system.net>
</configuration>

and

<?xml version="1.0" encoding="utf-8" ?>
<configuration>  
   <system.net>    
     <defaultProxy>      
          <proxy 
               proxyaddress="http://yourproxy.company.com:80" 
               usesystemdefault="True"
               autoDetect="False" />    
     </defaultProxy>  
   </system.net>
</configuration>

None of these worked.

What worked for me was this -

<system.net>    
    <defaultProxy enabled="true" useDefaultCredentials="false">
      <module type="WebPI.Net.AuthenticatedProxy, WebPI.Net, Version=1.0.0.0, Culture=neutral, PublicKeyToken=79a8d77199cbf3bc" />
    </defaultProxy>  
 </system.net>

The module needed to be registered with Web Platform Installer in order to use it.

Decasyllable answered 9/9, 2015 at 23:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.