C# – Connect to a WCF service (.svc) via a proxy (with username / password)

cwcfwcf-security

I've created a WCF service. I call it like this:

ServiceClient client = new ServiceClient ();
client.MyMethod();

So far so good on my machine.

Now I've deployed it in our DMZ (whatever that is), and I can call it via an outside URL (so the request from my machine goes out to the Internet and then goes to our datacenter).

But, we connect via a proxy to the Internet. I am not sure how that works, but I have to enter a proxy server in the connections, LAN settings section of Internet Explorer if I want to visit the Stack Overflow site.

When I don't change the code, I get this error:

The remote server returned an
unexpected response: (407) Proxy
Authentication Required ( The ISA
Server requires authorization to
fulfill the request. Access to the Web
Proxy filter is denied. ).

After googling, I found this code, but it leaves me with the same error.

  var b = client.Endpoint.Binding as System.ServiceModel.WSHttpBinding;
            b.ProxyAddress = new Uri("http://OURADDRESS.intern:8080");     
            b.BypassProxyOnLocal = false;     
            b.UseDefaultWebProxy = false;
            client.ClientCredentials.UserName.UserName = @"DOMAIN\USERNAME";
            client.ClientCredentials.UserName.Password = "myverysecretpassword";

Best Answer

In such a case, using the default proxy should be enough:

<configuration>
  <system.net>
    <defaultProxy useDefaultCredentials="true" />
  </system.net>
  ...
</configuration>

In your binding, you must only ensure using the default proxy (should be enabled by default):

b.UseDefaultWebProxy = true;

In case of manually setting credentials, I believe that your proxy expect Windows credentials and because of that this should be used:

client.ClientCredentials.Windows.ClientCredential.UserName = @"DOMAIN\USERNAME";
client.ClientCredentials.Windows.ClientCredential.Password = "myverysecretpassword";
Related Topic