Today I was working on deploying an update to a WCF service of mine that lives inside of a customers corporate network behind a proxy. This network, like most all other corporate networks, uses some form of a proxy for outbound traffic. If you're writing some custom logic to send web requests externally, you have full control over the request. For example, set the credentials used for the proxy authentication:
HttpWebRequest request = HttpWebRequest.Create(endPoint) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/xml; encoding='utf-8'";
request.Proxy = HttpWebRequest.GetSystemWebProxy();
request.UseDefaultCredentials = true;
request.Proxy.Credentials = new NetworkCredential("user", "password");
When working with 3rd party SDK's, the underlying HttpWebRequest instance is encapsulated from the user, where you really don't have much control over it. I ran into this issue today working with the Azure Service Bus SDK. Luckily, there's a more general way, that isn't specific to just Azure, that allows you to set proxy credentials on a more global basis.
Start off by creating a new class that inherits from IWebProxy.
public class CustomEnvironmentProxy : IWebProxy
{
public Uri GetProxy(Uri destination)
{
// specify the location of the proxy. you can dynamically control a proxy based on the destination parameter
return new Uri("http://myproxyurl");
}
public bool IsBypassed(Uri host)
{
// optionally bypass proxy authentication depending on the host request
return false;
}
public ICredentials Credentials
{
get
{
// return the NetworkCredential's to use against the proxy
return new NetworkCredential("username", "password");
}
set{}
}
}
Once you've built your project, head to the web.config of your web application and insert the following entry, where MyWebApplication is the namespace of the project, and CustomEnvironmentProxy is the name of your new class. The second MyWebApplication is the name of the DLL the new class is compiled within.
Now, every single web request will pass over your IWebProxy to determine credentials to be used.
Happy developing!