我有一堆远程机器都通过 HTTP 运行相同的 WCF 服务。我有一个中央配置实用程序,它需要在运行时决定要连接到哪些。我不想在配置文件中定义所有端点,因为这都是数据库驱动的。
我天真地试过这个:
CustomerServiceClient GetClientForIPAddress(string ipAddress)
{
string address = String.Format("http://{0}/customerservice.svc", ipAddress);
var client = new CustomerServiceClient("?", address);
return client;
}
其中 CustomerServiceClient 是我的服务引用代理类,但(不出所料)它给了我以下错误:
Could not find endpoint element with name '?' and contract 'SkyWalkerCustomerService.ICustomerService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element.
那么我如何在运行时声明一个端点并将我的服务引用指向它呢?
.NET 3.5
最佳答案
这是我用来在 silverlight 应用程序中配置端点的一段代码:
private void initEndpoint(ServiceEndpoint endPoint, string serviceName)
{
Uri hostUri = Application.Current.Host.Source;
string vdir = hostUri.LocalPath.Substring(0, hostUri.LocalPath.IndexOf("/ClientBin", StringComparison.InvariantCultureIgnoreCase));
string wcfBaseUri = string.Format("{0}://{1}:{2}{3}/WebServices/", hostUri.Scheme, hostUri.Host, hostUri.Port, vdir);
endPoint.Address = new EndpointAddress(new Uri(wcfBaseUri + serviceName));
}
传入的endPoint是要配置的端点,serviceName是服务的名称,如MyLoggingService.svc。我所做的就是将它指向一个新地址(在本例中是托管网站内的一个已知位置)。将其用作示例,并从任何地方传入您自己的字符串地址。
它是用一些看起来像这样的代码调用的:
_loggingService = new LoggingServiceClient();
initEndpoint(_loggingService.Endpoint, "LoggingService.svc");
希望这对您有所帮助。带着它跑,把它切碎,做成你自己的:)
关于.net - 在运行时指定 WCF 终结点的 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2498373/