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...


namespace TestNamespace

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



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".


         <service behaviorConfiguration="Default" name="TestNamespace.ServiceType">
            <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="TestNamespace.ServiceContract" />
baseAddress="http://localhost:8080/testservice" />

                <webHttp />


            <behavior name="Default">
                <serviceMetadata httpGetEnabled="true"/>


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


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


Comments have been disabled for this content.