2012-05-04 1 views
1

У меня есть служба WCF, размещенная в приложении winforms. Я использовал следующие ссылки:Тестовый клиент не может подключиться к службе WCF самостоятельно в приложении winforms

Когда я использую тестовый клиент WCF и попытаться добавить службу я получаю следующее сообщение об ошибке: Не удалось добавить службу. Метаданные службы могут быть недоступны. Убедитесь, что ваша служба запущена и подвержена метаданным.

Сведения об ошибке:

Error: Cannot obtain Metadata from http://localhost:8001/HelloWorld If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address.

For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange Error URI: http://localhost:8001/HelloWorld

Metadata contains a reference that cannot be resolved: 'http://localhost:8001/HelloWorld'.

There was no endpoint listening at http://localhost:8001/HelloWorld that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.

Unable to connect to the remote server No connection could be made because the target machine actively refused it 127.0.0.1:8001HTTP GET Error URI: http://localhost:8001/HelloWorld

There was an error downloading 'http://localhost:8001/HelloWorld'.

Unable to connect to the remote server

No connection could be made because the target machine actively refused it 127.0.0.1:8001

Вот мой код:

public Server() 
{ 
    InitializeComponent(); 

    using (host = new ServiceHost(typeof(HelloWorldService), new Uri("http://localhost:8001/HelloWorld"))) 
    { 
     // Check to see if the service host already has a ServiceMetadataBehavior 
     ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>(); 
     // If not, add one 
     if (smb == null) 
      smb = new ServiceMetadataBehavior(); 
     smb.HttpGetEnabled = true; 
     smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; 
     host.Description.Behaviors.Add(smb); 

     //You need to add a metadata exchange (mex) endpoint to your service to get metadata. 
     host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); 

     //http 
     host.AddServiceEndpoint(typeof(IHelloWorldService), new WSHttpBinding(), ""); 

     host.Open(); 
    } 
} 

[ServiceContract] 
public interface IHelloWorldService 
{ 
    [OperationContract] 
    string SayHello(string name); 
} 

public class HelloWorldService : IHelloWorldService 
{ 
    public string SayHello(string name) 
    { 
     return string.Format("Hello, {0}", name); 
    } 
} 
+0

Заблокирован порт 8001? –

+0

@ jskiles1 Я отключил брандмауэр Windows. Все еще не работает. – Mausimo

ответ

1

Я не уверен, почему, но переключение метода use() {} в try {} .. catch {} позволяет этому коду функционировать должным образом. Клиент Тест WCF может успешно добавить службу и я могу перейти к запущенной службы через: http://localhost:8001/HelloWorld

+2

Это потому, что использование заканчивается удалением вашего сервиса. Добавьте 'Console.ReadLIne()' или что-нибудь подобное, чтобы приостановить выполнение после 'host.Open()', и оно будет работать даже с 'use'. –

+0

@WiktorZychla Спасибо, это имеет смысл сейчас. – Mausimo

0

кажется первопричина на дне:

Unable to connect to the remote server No connection could be made because the target machine actively refused it 127.0.0.1:8001

Я хотел бы проверить журнал событий чтобы проверить, не вызван ли вызов host.Open() (возможно, из-за брандмауэра или что-то еще), или пройти через него с помощью отладчика затем используйте telnet, чтобы узнать, действительно ли он прослушивает 8001.

+0

Я запустил программу и попытался использовать telnet. «telnet 127.0.0.1 8001». Я получаю «Подключение к 127.0.0.1 ... Не удалось открыть соединение с хостом на порту 8001:« Не удалось подключиться ». Я обернулся брандмауэром Windows, проверяя это. Когда вы переходите через код с отладчиком, host.open() не генерирует исключение ... – Mausimo

+0

Вы имеете в виду Windows event viewer? – Mausimo

0

Вот решение для этого Попробуйте это будет работать

Uri baseAddress = new Uri("http://localhost:8001/HelloWorld"); 

    // Create the ServiceHost. 
    using (serviceHost = new ServiceHost(typeof(HelloWorldService), baseAddress)) 
    { 
     // Enable metadata publishing. 
     ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); 
     smb.HttpGetEnabled = true; 
     smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; 
     serviceHost.Description.Behaviors.Add(smb); 

     // Open the ServiceHost to start listening for messages. Since 
     // no endpoints are explicitly configured, the runtime will create 
     // one endpoint per base address for each service contract implemented 
     // by the service. 
     serviceHost.AddServiceEndpoint(typeof(IHelloWorldService), new WSHttpBinding(), ""); 
     serviceHost.Open(); 

    } 
Смежные вопросы