Recently Microsoft added REST support to WCF services. So what RESTful service means?
“A RESTFul web service is a simple web service implemented using HTTP and the principles of REST. Such a web service can be thought about as a collection of resources. The definition of such a web service can be thought of as comprising three aspects:
- The URI for the web service such as
- The YAML but can be anything.
- The set of operations supported by the web service using HTTP methods including but not limited to POST, GET, PUT and DELETE.
Members of the collection are addressed by ID using URIs of the form <baseURI>/<ID>. The ID can be any unique identifier. For example if a RESTFul web service representing a collection of cars for sale might have the URI
http://example.com/resources/cars. If the service uses the car registration number as the ID then a particular car might be present in the collection as
<%@ ServiceHost Language="C#" Debug="true" Service="FetchChildItems" CodeBehind="~/App_Code/FetchChildItems.cs" %>
IFetchChildItems.cs contains your interface definitions:
Implementing a service and instructing it to return XML,JSON output
Next step you need to do is actually instruct your service to return your defined types in JSON or XML format.
In svc file you need to define what factory is processing WCF service request:
WebServiceHost in managed hosting environments where the host instance is created dynamically in response to incoming messages.
In IFetchChildItems.cs you need to specify that service will be executed when consumer calls web url endpoint. In order to do it you need to specify custom attribute WebInvoke (System.ServiceModel.Web namespace )
WebMessageBodyStyle BodyStyle is giving you ability to specify how your service response will be formatted
UriTemplate allows you define your REST contract, WCF automatically extracts defined variables from URL and passing it values as parameters to service method
Defining Endpoint for REST WCF service in web.config
First you need to enable ASP.NET Compatibility Mode in serviceHostingEnvironment section:
Please note that binding attribute is set to binding=”webHttpBinding”
Behavior should include webHttp element