WCF - Using WebHttpBinding for REST services

You can use WebHttpBinding to have REST endpoints in your WCF application to expose simple public service calls. 

Use a UriTemplate in your service contract and a WebHttpBinding endpoint.  Here's an example...


  (IContractName.cs)

namespace TestNamespace
{

    [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);
    }

}

(ServiceType.cs)

namespace TestNamespace
{

    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");
        }
    }

}


Creating a WebHttpBinding endpoint into your WCF service. 

If you get a "The Address property on ChannelFactory.Endpoint was null." exception, make sure to add a "behaviorConfiguration" property to your endpoint.  This value should point to a custom defined "endpointBehavior".

 (App.config)

<system.serviceModel>
    <services>
         <service behaviorConfiguration="Default" name="TestNamespace.ServiceType">
            <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="TestNamespace.ServiceContract" />
            <host>
                <baseAddresses>
                    <add
baseAddress="http://localhost:8080/testservice" />
                </baseAddresses>
            </host>
        </service>
    </services>
    <behaviors>

        <endpointBehaviors>
            <behavior
name="webBehavior">
                <webHttp />
            </behavior>
        </endpointBehaviors>

        <serviceBehaviors>

            <behavior name="Default">
                <serviceMetadata httpGetEnabled="true"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>

 


Using your browser to point to http://localhost:8080/testservice/date/1995/10/10 , the result will look like this:

testservice 


Moving futher ..... If you would like to add this running service into another application like a Web application, use a WebChannelFactory in your application.

 

WebChannelFactory<IContractName> cf = new WebChannelFactory<IContractName>(new Uri("http://localhost:8080/testservice"));
ServiceType channel = cf.CreateChannel();
string testDate = channel.GetDate("1995","10","10");

20 Comments

Comments have been disabled for this content.