2012-12-07 2 views
1

У меня есть служба WCF, которая является самообслуживающей службой Windows. При отладке с тестовым клиентом WCF служба работает отлично. Я использую Javascript с простыми ajax-запросами, которые возвращают JSON. Хотя, когда я запускаю службу в качестве службы Windows, запрос получает ошибку 400. Я предполагаю, что это может иметь какое-то отношение к моей конфигурации.WCF Service работает в отладке, но не как служба Windows

Любая помощь приветствуется.

Test Client WCF Config

<system.serviceModel> 
    <bindings> 
     <wsHttpBinding> 
      <binding name="MetadataExchangeHttpBinding_ISkyMobileService"> 
       <security mode="None" /> 
      </binding> 
     </wsHttpBinding> 
    </bindings> 
    <client> 
     <endpoint address="http://localhost:8523/HLT/Sky/SkyMobileService/mex" 
      binding="wsHttpBinding" bindingConfiguration="MetadataExchangeHttpBinding_ISkyMobileService" 
      contract="ISkyMobileService" name="MetadataExchangeHttpBinding_ISkyMobileService" /> 
    </client> 
</system.serviceModel> 

службы Windows App.Config

<system.serviceModel> 
    <services> 
     <service name="HLT.Sky.MobileDeviceServices.SkyMobileService" behaviorConfiguration="HeliosMobileServiceBehavior"> 
     <host> 
      <baseAddresses> 
      <add baseAddress="http://localhost:8523/HLT/Sky/SkyMobileService" /> 
      </baseAddresses> 
     </host> 
     <endpoint address="" binding="webHttpBinding" contract="HLT.Sky.MobileDeviceServices.ISkyMobileService" bindingNamespace="http://HLT.Sky.MobileDeviceServices" /> 
     <endpoint address="mex" binding="mexHttpBinding" contract="HLT.Sky.MobileDeviceServices.ISkyMobileService" bindingNamespace="http://HLT.Sky.MobileDeviceServices" /> 
     </service> 
    </services> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior name="SkyMobileServiceBehavior"> 
      <serviceMetadata httpGetEnabled="true"/> 
      <serviceDebug includeExceptionDetailInFaults="false"/> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    </system.serviceModel> 

службы Windows Реализация

using System.ServiceProcess; 
using System.ServiceModel; 


namespace HLT.Sky.WindowsService1 
{ 
    public partial class Service1 : ServiceBase 
    { 
     internal static ServiceHost myServiceHost = null; 

     public Service1() 
     { 
      InitializeComponent(); 
     } 

     protected override void OnStart(string[] args) 
     { 
      if (myServiceHost != null) 
      { 
       myServiceHost.Close(); 
      } 
      myServiceHost = new ServiceHost(typeof(MobileDeviceServices.SkyMobileService)); 
      myServiceHost.Open(); 
     } 

     protected override void OnStop() 
     { 
      if (myServiceHost != null) 
      { 
       myServiceHost.Close(); 
       myServiceHost = null; 
      } 
     } 
    } 
} 

WCF интерфейс

#region GET 
    // Return JSON Store for specified chartType 
    [OperationContract] 
    [WebGet(UriTemplate = "GetChartData?chartType={chartType}&serialNumber={serialNumber}&_dc={dc}&limit={limit}&callback={callback}", ResponseFormat = WebMessageFormat.Json)] 
    string GetChartData(string dc, string limit, string callback, int chartType, string serialNumber); 

    [OperationContract] 
    [WebGet(ResponseFormat = WebMessageFormat.Json)] 
    string GetHomePageData(); 
    #endregion 

    #region POST 
    [OperationContract] 
    [WebInvoke(Method = "POST", UriTemplate = "VerifyPINData?pinData={pinData}", ResponseFormat = WebMessageFormat.Json)] 
    bool VerifyPINData(string pinData); 

    [OperationContract] 
    [WebInvoke(Method = "POST", UriTemplate = "SubmitCNPData?cnpData={cnpData}&serialNumber={serialNumber}", ResponseFormat = WebMessageFormat.Json)] 
    bool SubmitCNPData(int cnpData, string serialNumber); 

    [OperationContract] 
    [WebInvoke(Method = "POST", UriTemplate = "SendEmail?mailTo={mailTo}&subject={subject}&message={message}",ResponseFormat = WebMessageFormat.Json)] 
    bool SendEmail(string mailTo, string subject, string message); 

    #endregion 

Program.cs

static void Main() 
    { 
     ServiceBase[] ServicesToRun; 
     ServicesToRun = new ServiceBase[] 
     { 
      new Service1() 
     }; 
     ServiceBase.Run(ServicesToRun); 
    } 
+1

Вы можете описать, как вы получили свой wcf для работы в службах Windows. вы должны внедрить метод start в классе службы Windows и включить самостоятельно размещенную wcf. – Dmitry

+0

Попробуйте устранить проблему с помощью Fidler. – abatishchev

+0

Также старайтесь размещать в IIS вместо самостоятельной службы Windows. – abatishchev

ответ

1

Добавление поведения конечной точки и удаление "Mex" конечная точка в конечном итоге решения данной проблемы. См. Рабочий файл конфигурации ниже:

<system.serviceModel> 
    <client> 
     <endpoint binding="webHttpBinding" bindingConfiguration="" contract="HLT.Sky.MobileDeviceServices.ISkyMobileService" /> 
    </client> 
    <services> 
     <service name="HLT.Sky.MobileDeviceServices.SkyMobileService" behaviorConfiguration="SkyMobileServiceBehavior"> 
     <host> 
      <baseAddresses> 
      <add baseAddress="http://localhost:8523/HLT/Sky/SkyMobileService" /> 
      </baseAddresses> 
     </host> 
     <endpoint address="" binding="webHttpBinding" contract="HLT.Sky.MobileDeviceServices.ISkyMobileService" /> 
     </service> 
    </services> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior name="SkyMobileServiceBehavior"> 
      <serviceMetadata httpGetEnabled="true"/> 
      <serviceDebug includeExceptionDetailInFaults="true"/> 
     </behavior> 
     </serviceBehaviors> 
      <endpointBehaviors> 
     <behavior> 
      <webHttp/> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 
    </system.serviceModel> 
+0

Приятно, что вы это решили, но вы говорите: «Хотя, когда я запускаю службу в качестве службы Windows, запрос получает ошибку 400. Я предполагаю« _. Вы не должны угадывать, вы должны найти ошибку и исправить это. Без конечной точки mex вам придется вернуться к WSDL, и это не всегда идеальный вариант. – CodeCaster

+0

@CodeCaster Хорошая точка. Я знаю, что это связано с моей конфигурацией.Я просто знаю, когда добавляю конечную точку mex, я получаю статус HTTP 200, но данные не возвращаются. Когда я удаляю его, я получаю данные. Я не совсем понимаю, почему это так. – fortune

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