Search code examples
c#.netwcfapp-configwebhttpbinding

WebHttpBinding in WCF: how to configure it the proper way?


Trying to follow this example to make it work: http://weblogs.asp.net/kiyoshi/archive/2008/10/08/wcf-using-webhttpbinding-for-rest-services.aspx

Here is my App.config:

<system.serviceModel>
   <services>      
      <!-- The service for the TEST WEB client -->
      <service name="MyServer.AAServiceType" behaviorConfiguration="Default">
         <endpoint address="testservice" 
                   binding="webHttpBinding" behaviorConfiguration="webBehavior"
                   contract="MyServer.AAIContractName" />
         <host>
            <baseAddresses>
               <add baseAddress="http://localhost:8787/" />
            </baseAddresses>
         </host>
      </service>
    </services>
    <behaviors>
       <serviceBehaviors>
          <!-- TEST WEB BEHAVIOR -->
          <behavior name="Default">
             <serviceMetadata httpGetEnabled="true"/>
          </behavior>
       </serviceBehaviors>
       <!-- TEST WEB ENDPOINT -->
       <endpointBehaviors>
          <behavior name="webBehavior">
             <webHttp />
          </behavior>
       </endpointBehaviors>
   </behaviors>
</system.serviceModel>

Update: The service contract is:

namespace MyServer
{
    [ServiceContract(SessionMode=SessionMode.NotAllowed)] 
    public interface IContractName 
    { 
        [WebGet(UriTemplate = "date/{year}/{month}/{day}", ResponseFormat = WebMessageFormat.Xml)] 
        [OperationContract] 
        string GetDate(string day, string month, string year); 
    }

    public class ServiceType : IContractName 
    {  
        public string GetDate(string day, string month, string year) 
        { 
           return new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day)).ToString("dddd, MMMM dd, yyyy"); 
        } 
    }
}

The problem is that when I am trying to connect to 8787 port (using putty, for instance) a "Connection refused" error is returned. As you can see, I've also tried to put the wrong names in contract class and service implementation and got no exceptions. What am I doing wrong, please?


Solution

  • There was an error in the code that launched the service. The correct code is:

    using (ServiceHost serviceHost = new ServiceHost(typeof(ServiceType)))
    {
        try
        {
          // Open the ServiceHost to start listening for messages.
          serviceHost.Open();
    
          // The service can now be accessed.
          Console.WriteLine("The service is ready.");
          Console.WriteLine("Press <ENTER> to terminate service.");
          Console.ReadLine();
    
          // Close the ServiceHost.
          serviceHost.Close();
        }
        catch (CommunicationException commProblem)
        {
          Console.WriteLine(commProblem.Message);
          Console.ReadLine();
        }
    }