easy upgrade WCF Service to RESTful

Why?

We are in kind of dilemma of choosing the architecture for our upcoming web applications. MVC or SL4? Because the first few pages we are going to build are quite simple, so I prefer to make it on REST+jQueryUI for now. It should be very easy to switch to either one in the future.

We already have the WCF service built, the only challenge is to make it RESTful.

How?

WebGet

Add webGet attribute/verb on Contract. Default response type is xml.

[ServiceContract]
public interface ICountryProvinceWCFService
{

    [OperationContract]
    [WebGet(ResponseFormat=WebMessageFormat.Json)]
    string[] GetProvinceGET(string Country);
}

behaviorConfiguration

According to ms help WegGet is useless until web http behavior is defined in web.config.

Note: this is a endpoint behavior, not service behavior, this must be set on endpoint level.

Also, binding type needs to be webHttpBinding.

    <services>
      <service behaviorConfiguration="DefaultServicesBehavior" name="MyWcfService">
        <endpoint address="" binding="wsHttpBinding" contract="IMyWcfService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <endpoint address="rest" binding="webHttpBinding" contract="IMyWcfService" behaviorConfiguration="RestfulWebServiceEndpointBehavior" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost/RestDemo" />
          </baseAddresses>
        </host>
      </service>

...
    <behaviors>
      <endpointBehaviors>
        <behavior name="RestfulWebServiceEndpointBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>

    </behaviors>

ref:

http://www.codeproject.com/KB/aspnet/WCF_JQUERY_ASMX.aspx

Advertisements