WCF Rest

Creating a REST style interface with WCF is fairly simple. The steps are listed briefly below, and in more depth below the list of steps.

1. Create your interface/service contract
2. Annotate the methods with WebGet or WebInvoke attributes
3. Create the implementation of the interface
4. Declare the endpoint within the configuration file (or in code). The binding should be webHttpBinding and should have an endpoint behaviour specificied with WebHttp
5. If need be declare the http baseAddress

In more depth

1. Create your interface/service contract
and
2. Annotate the methods with WebGet or WebInvoke attributes

[ServiceContract]
public interface IRestService
{
   [OperationContract]
   [WebGet(UriTemplate = "projects")]
   IList GetProjects();

   [OperationContract]
   [WebGet(UriTemplate = "execute/{projectName}")]
   void Execute(string projectName);
}

Note: Note to self. Don’t forget to put the ServiceContract attribute on the interface !

I’ve implemented both methods a GET methods. Assuming a baseAddress of http://localhost:8733/MyService/ to call these methods through a web browser we can simply type http://localhost:8733/MyService/projects and http://localhost:8733/MyService/execute/MyProject respectively.

3. Create the implementation of the interface

No need to list source code for this, simple implement the interface you created.

4. Declare the endpoint within the configuration file (or in code). The binding should be webHttpBinding and should have an endpoint behaviour specificied with WebHttp
and
5. If need be declare the http baseAddress

The key bit to getting everything to work is the configuration file. I’m self hosting for this example so implementing the code in the App.config

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="rest">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="StandardPlugins.MonitorService">
        <endpoint address="" binding="webHttpBinding" bindingConfiguration=""
            contract="StandardPlugins.IRestService" behaviorConfiguration="rest">
        </endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8733/MyService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
</system.serviceModel>

Note: The REST methods should be accessible via HTTP, hence the binding is webHttpBinding and the baseAddress is http. A behaviorConfiguration is required with the webHttp element.

Further reading

http://msdn.microsoft.com/en-us/magazine/dd315413.aspx#id0070050
http://msdn.microsoft.com/en-us/library/vstudio/bb412172(v=vs.90).aspx