WCF发现找到端点但主机是“localhost”

时间:2010-03-24 14:09:23

标签: c# wcf service-discovery

我正在尝试使用http://msdn.microsoft.com/en-us/library/dd456783(v=VS.100).aspx作为起点在WCF中使用发现功能。它在我的机器上工作正常,但后来我想在另一台机器上运行该服务。该服务被正确发现,但找到的服务的主机名始终是“localhost”,当然没什么用处。

服务端点:

var endpointAddress = new EndpointAddress(new UriBuilder { Scheme = Uri.UriSchemeNetTcp, Port = port}.Uri);
var endpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(IServiceInterface)), new NetTcpBinding (), endpointAddress);

客户端:

static EndpointAddress FindServiceAddress<T>()
{
  Stopwatch stopwatch = new Stopwatch();
  stopwatch.Start();
  DiscoveryClient discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint());
  // Find  endpoints            
  FindResponse findResponse = discoveryClient.Find(new FindCriteria(typeof(T)));
  Console.WriteLine(string.Format("Searched for {0} seconds. Found {1} Endpoint(s).",stopwatch.ElapsedMilliseconds / 1000,findResponse.Endpoints.Count));
  if (findResponse.Endpoints.Count > 0)
  {
     return findResponse.Endpoints[0].Address;
  }
  return null;
 }

我应该简单地将主机设置为System.Environment.MachineName吗?

2 个答案:

答案 0 :(得分:8)

在做了一些搜索之后我发现没有其他解决方案而不是使用System.Environment.MachineName

 new EndpointAddress(new UriBuilder {Scheme = Uri.UriSchemeNetTcp, Port = port, Host = System.Environment.MachineName}.Uri);

答案 1 :(得分:8)

我花了很多时间来研究这个问题。在代码中构建基地址对我来说是不可接受的,因为它意味着硬编码传输方案和端口(当然,后者可以存储在单独的配置部分中,但为什么不仅仅使用现有部分?)。我希望能够像往常一样在config中配置基地址。事实证明,像<add baseAddress="net.tcp://*:8731/"/>这样的基地址将完美起作用。我认为程序化配置也是如此。