I’m mainly doing javascript in my free time, but at work, it’s still classic .NET. Yesterday, I had to quickly set up a REST service via WCF to test something. In the spirit of saving my keystrokes, and for my own later reference, I’m posting how to do it here, instead of emailing it.
I’m assuming you have an existing WCF service.
Just add the following to your ServiceContract (you’ll need a reference to System.ServiceModel.Web):
[OperationContract] [WebGet(UriTemplate = "{id}", ResponseFormat = WebMessageFormat.Json)] Person GetPerson(string id);
For REST to work, your parameters will have to be a string and you will have to parse it in the implementation of your ServiceContract.
I want JSONP, so I’ve added the response format and need some extra stuff in my config:
The service:
<endpoint address="People" binding="webHttpBinding" bindingConfiguration="Default" behaviorConfiguration="jsonBehavior" contract="My.Contracts.IPersonService" />
A behavior:
<endpointBehaviors> <behavior name="jsonBehavior"> <webHttp /> </behavior> </endpointBehaviors>
Finally, the binding:
<webHttpBinding> <binding name="Default" crossDomainScriptAccessEnabled="true" /> </webHttpBinding>
If you need other REST methods (POST for example), have a look at WebInvoke.
Now you can navigate to your url, for example: http://www.example.com/People/3, or use this url for AJAX calls.