How to define the LocalEndPoint to use by a WCF client when calling a WCF service (if the client machine has multiple IP addresses) ?
I have a machine located
Had a hard time finding the answer to this one myself, so i'll share my solution in case someone else comes by here.
Below is a method that returns a wcf soapservice. The code will try to use a specific ip if available. I did this check to have it working on a test machine as well.
public static proposalSoapClient getService()
{
string serviceurl = "http://somesite.dk/proposal.asmx";
var localIpAddress = IPAddress.Parse("123.123.123.123");
var hasLocalAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Any(ip => ip.AddressFamily == AddressFamily.InterNetwork && ip.Equals(localIpAddress));
var binding = new System.ServiceModel.BasicHttpBinding("proposalSoap"); //name of binding in web.config
var endpoint = new EndpointAddress(serviceurl);
ServicePoint servicePoint = ServicePointManager.FindServicePoint(new Uri(serviceurl));
servicePoint.BindIPEndPointDelegate = (sp, rm, retryCount) => { return new IPEndPoint(hasLocalAddress ? localIpAddress : IPAddress.Any, 0); };
return new proposalSoapClient(binding, endpoint);
}
Also when i am on the test server i had to use a proxy to get to the service. (i used fiddler as proxy on the machine that had access to the service). Below is the same code but with added section for proxy when on the test server.
public static proposalSoapClient getService()
{
string serviceurl = "http://somesite.dk/proposal.asmx";
var localIpAddress = IPAddress.Parse("123.123.123.123");
var hasLocalAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Any(ip => ip.AddressFamily == AddressFamily.InterNetwork && ip.Equals(localIpAddress));
var binding = new System.ServiceModel.BasicHttpBinding("proposalSoap"); //name of binding in web.config
var endpoint = new EndpointAddress(serviceurl);
ServicePoint servicePoint = ServicePointManager.FindServicePoint(new Uri(serviceurl));
#if DEBUG
Uri proxyUri = new Uri("http://someothersite.dk:8888");
binding.ProxyAddress = proxyUri;
binding.BypassProxyOnLocal = false;
binding.UseDefaultWebProxy = false;
servicePoint = ServicePointManager.FindServicePoint(serviceurl, new WebProxy(proxyUri, false));
#endif
servicePoint.BindIPEndPointDelegate = (sp, rm, retryCount) => { return new IPEndPoint(hasLocalAddress ? localIpAddress : IPAddress.Any, 0); };
return new proposalSoapClient(binding, endpoint);
}