.net - 在运行时指定 WCF 终结点的 IP 地址

标签 .net wcf

我有一堆远程机器都通过 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/

相关文章:

.net - 如何在 .NET Framework 中更新浏览器功能的定义?

wcf - 为受 SSL 保护的 WSIT/Metro Web 服务和客户端设置身份验证

c# - 如何通过用户凭据访问 AD FS 声明?

c# - 如何从我的 C# 测试访问服务日志?

c# - 如何在 dotnetnuke 框架中创建 Web 应用程序?

.net - 有专门为 OpenCV 2.2 写的书吗?

c# - 如何在 Surface 4 Pro 中禁用 WPF 平板电脑支持?

c# - 如何解释 BenchmarkDotNet 和 dotMemory 的结果?

c# - 让 POST 或 PUT 在 WCF REST 服务中工作

wcf - ASP.Net WCF 服务的 Thread.CurrentPrincipal 被联合 (WIF) 环境中的某些拦截器丢弃