2012-03-28 3 views
3

Я хочу создать службу, которая предоставляет конечную точку basicHTTP и конечную точку webHTTP. Если я тестирую следующий проект с VS2010 в режиме работы, все в порядке; но я хочу разместить службу в IIS (локально или удаленно) и пройти тесты.Служба WCF, размещенная на IIS, не работает

Service.svc:

<%@ ServiceHost Language="C#" Debug="true" Service="ContactLibrary.ContactLibraryService"%> 

Я разместить свой веб-сайт в локальной IIS. Когда я попробовать: http://localhost/ContactLibrary2.0/Service.svc я получаю:

типа «ContactLibrary.ContactLibraryService», если в качестве службы значение атрибута в директиве ServiceHost или предусмотрено в конфигурации элемента system.serviceModel/serviceHostingEnvironment/serviceActivations не может быть найден ,

Web.config выглядит следующим образом:

<?xml version="1.0"?> 
<configuration>  
    <system.web> 
    <compilation debug="false" targetFramework="4.0" /> 
    </system.web> 
    <system.serviceModel> 
    <services> 
     <service name="ContactLibraryNamespace.ContactLibraryService"> 
     <endpoint address="" binding="basicHttpBinding" bindingConfiguration="" 
      name="soap" contract="ContactLibraryNamespace.IContact" /> 
     <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="" 
      name="mex" contract="IMetadataExchange" /> 
     <endpoint address="rest" behaviorConfiguration="web" binding="webHttpBinding" 
      bindingConfiguration="" name="rest" /> 
     <host> 
      <baseAddresses> 
      <add baseAddress="http://localhost/ContactLibrary2.0" /> 
      </baseAddresses> 
     </host> 
     </service> 
    </services> 
    <behaviors> 
     <endpointBehaviors> 
     <behavior name="web"> 
      <webHttp /> 
      <dataContractSerializer maxItemsInObjectGraph="2147483647"/> 
     </behavior> 
     </endpointBehaviors> 
     <serviceBehaviors> 
     <behavior name=""> 
      <serviceMetadata httpGetEnabled="true" /> 
      <serviceDebug includeExceptionDetailInFaults="true" /> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 
    <system.webServer> 
    <modules runAllManagedModulesForAllRequests="true"/> 
    </system.webServer>  
</configuration> 

IContact выглядит следующим образом:

[ServiceContract] 
    public interface IContact 
    { 
     [OperationContract] 
     [WebInvoke(Method = "GET", UriTemplate = "GetContact/{idContact}", ResponseFormat = WebMessageFormat.Json)] 
     Contact GetContact(string idContact); 
     [OperationContract] 
     [WebInvoke(Method = "POST", UriTemplate = "AddContact", RequestFormat = WebMessageFormat.Json)] 
     string AddContact(Contact contact); 
     [OperationContract] 
     [WebInvoke(Method = "POST", UriTemplate = "EditContact", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)] 
     string EditContact(string idContact, Contact Contact); 
     [OperationContract] 
     [WebInvoke(Method = "POST", UriTemplate = "DeleteContact", RequestFormat = WebMessageFormat.Json)] 
     string DeleteContact(string idContact); 
     [OperationContract] 
     [WebInvoke(Method = "GET", UriTemplate = "GetAllContacts/{start}/{end}", RequestFormat = WebMessageFormat.Json)] 
     List<Contact> GetAllContacts(string start, string end);   
    } 
+0

Не могли бы вы разместить свой интерфейс IContact? –

+0

Все выглядит хорошо. Но я не вижу конечной точки для ContactLibraryJSONService. У вас есть такая конечная точка? Если нет, вы должны добавить его. – paramosh

+0

Я еще не добавил один, потому что хочу видеть, как эта часть работает. Я хочу видеть, что мои ответы службы на WCFStorm. –

ответ

2

В файле SVC необходимо связать код позади как показано ниже:

<%@ ServiceHost Language="C#" Debug="true" Service="ContactLibraryNamespace.ContactLibrarySOAPService" CodeBehind="ContactLibrarySOAPService.svc.cs" %> 

Вам не нужно иметь отдельные классы для использования Basi cHttpBinding и webHttpBinding.

Просто изменить интерфейс IContact к ниже:

[ServiceContract] 
    public interface IContact 
    { 
     [OperationContract] 
     [WebInvoke(Method="GET", UriTemplate = "GetContact/{idContact}", ResponseFormat=WebMessageFormat.Json)] 
     Contact GetContact(string idContact); 
     [OperationContract] 
     [WebInvoke(Method = "POST", UriTemplate = "AddContact", RequestFormat = WebMessageFormat.Json)] 
     string AddContact(Contact contact); 
     [OperationContract] 
     [WebInvoke(Method = "POST", UriTemplate = "EditContact", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)] 
     string EditContact(string idContact, Contact Contact); 
     [OperationContract] 
     [WebInvoke(Method = "POST", UriTemplate = "DeleteContact", RequestFormat = WebMessageFormat.Json)] 
     string DeleteContact(string idContact); 
     [OperationContract] 
     [WebInvoke(Method = "GET", UriTemplate = "GetAllContacts/{start}/{end}", RequestFormat = WebMessageFormat.Json)] 
     List<Contact> GetAllContacts(string start, string end);   
    } 

Затем измените элемент службы в вашей конфигурации, чтобы:

<system.serviceModel> 
    <services> 
     <service name="ContactLibraryNamespace.ContactLibrarySOAPService"> 
     <endpoint address="" binding="basicHttpBinding" bindingConfiguration="" 
     contract="ContactLibraryNamespace.IContact" /> 
     <endpoint address="rest" behaviorConfiguration="web" binding="webHttpBinding" bindingConfiguration="" contract="ContactLibraryNamespace.IContact" /> 
     <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="" 
     contract="IMetadataExchange" /> 
     <host> 
      <baseAddresses> 
      <add baseAddress="http://localhost/ContactLibrary2.0" /> 
      </baseAddresses> 
     </host> 
     </service> 
    </services> 
    <behaviors> 
     <endpointBehaviors> 
     <behavior name="web"> 
      <webHttp /> 
      <dataContractSerializer maxItemsInObjectGraph="2147483647"/> 
     </behavior> 
     <behavior name="json"> 
      <enableWebScript /> 
      <dataContractSerializer maxItemsInObjectGraph="2147483647"/> 
     </behavior> 
     </endpointBehaviors> 
     <serviceBehaviors> 
     <behavior> 
      <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> 
      <serviceMetadata httpGetEnabled="true"/> 
      <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> 
      <serviceDebug includeExceptionDetailInFaults="false"/> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 

Это подвергнет ваш интерфейс IContact доступны через SOAP и REST.

Единственное изменение будет конечной точки URL REST, который был бы http://localhost/virtualDirectoryname/ContactLibrarySOAPService.svc/rest/resourcename

Примечание: Измените имя класса, который реализует IContact таким образом, чтобы сделать его родовое, а не имеющие слово SOAP или REST, чтобы избежать путаницы ,

+0

<имя поведение = "JSON"> \t Кто "JSON"? У меня нет никакого кода, и у меня нет класса cs под * .svc. –

+0

вместо использования кода позади я использую ссылку на мой проект C#. Это неправильно или плохо? –

+0

Я отредактировал мой вопрос с последними изменениями/ошибками в моем проекте. –

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