WCF: HTTP 400 неверный запрос на самообслуживание - PullRequest
1 голос
/ 07 декабря 2011

У меня есть этот интерфейс:

  [ServiceContract]
    public interface ILocationService
    {
        [OperationContract]
        bool RegisterForNotification(string name, string uri);

        [OperationContract]
        bool UnRegisterForNotification(string name);
    }

и этот сервис:

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class LocationBasedService : ILocationService
    {
        #region Registrations
        public bool RegisterForNotification(string name, string uri)
        {
            return true;
        }

        public bool UnRegisterForNotification(string name)
        {
            return true;
        }     
        #endregion
    }

и следующая конфигурация:

<configuration>
  <system.serviceModel>
    <services>
      <service name="PushNotifications.Server.Service.LocationBasedService" >
        <endpoint address="http://localhost:8000/LocationBasedService"
                 binding="basicHttpBinding"                 
                 contract="Services.Interface.ILocationService"/>
      </service>      
    </services>
  </system.serviceModel>

Самостоятельно размещен в приложении WPFиспользуя ServiceHost.Код для этого выглядит следующим образом:

private void startSrv_Click(object sender, RoutedEventArgs e)
        {
            try 
            {
                host = new ServiceHost(typeof(LocationBasedService));
                host.Open();
                AddDiagnosticMessage("service successfully initialized");
                AddDiagnosticMessage(string.Format("{0} is up and running with these end points", host.Description.ServiceType));
                foreach (var se in host.Description.Endpoints)
                    AddDiagnosticMessage(se.Address.ToString());
            }
            catch (TimeoutException ex)
            {
                AddDiagnosticMessage(string.Format("The service operation timeod out. {0}", ex));
            }
            catch (CommunicationException ex)
            {
                AddDiagnosticMessage(string.Format("Could not start host service. {0}", ex));
            }
            catch (Exception ex)
            {
                AddDiagnosticMessage(ex.Message);
            }                  
        }

Служба запускается без исключений.Однако, когда я отправляю URL http://localhost:8000/LocationBasedService в свой браузер, я получаю HTTP 400 Bad Request.Если я пытаюсь создать клиент WCF, используя ссылку на службу Visual Studio, я получаю следующую ошибку:

'http://localhost:8000/LocationBasedService'. Тип содержимого application / soap + xml;charset = utf-8 не поддерживается службой http://localhost:8000/LocationBasedService. Привязки клиента и службы могут не совпадать.Удаленный сервер возвратил ошибку: (415) Невозможно обработать сообщение, потому что тип содержимого 'application / soap + xml;charset = utf-8 'не был ожидаемым типом' text / xml;charset = utf-8 '.. Если служба определена в текущем решении, попробуйте создать решение и снова добавить ссылку на службу.

ЕСЛИ я пытаюсь вызвать клиента, используя следующий код, я получаюисключение тайм-аута.

 private void Button_Click(object sender, RoutedEventArgs e)
        {
            statusMessages.Add(GetFormattedMessage("initiailing client proxy"));
            var ep = new EndpointAddress("http://localhost:8000/LocationBasedService");
                     var proxy = ChannelFactory<ILocationService>.CreateChannel(new BasicHttpBinding(), ep);          
            var register = proxy.RegisterForNotification("name1", @"http://google.com");
            if (register)
            {  Console.Writeline(register.ToString()); }
        }

Может, кто-нибудь подскажет, что я пропустил.Это должно было быть легким упражнением:!

TIA.

1 Ответ

2 голосов
/ 07 декабря 2011

Плохой HTTP-запрос был решен добавлением этого кода:

 host = new ServiceHost(typeof(LocationBasedService), new Uri("http://localhost:8000/LocationBasedService"));

  // Enable metadata publishing.
   ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
   smb.HttpGetEnabled = true;
   smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
   host.Description.Behaviors.Add(smb);

    host.Open();   

Что касается времени ожидания службы, то это было вызвано моим персональным брандмауэром. Мне пришлось добавить Visual Studio в список разрешенных приложений.

Вернуться в бизнес.

...