Using WCF Services, it is possible to expose a REST endpoint. This way, we can easily create a WCF services project in which some services have a SOAP endpoint while others have a REST endpoint.
In .NET 4.0, there are several ways to create REST services. In this example, we'll use a manual approach based on the WebHttpBinding
. This process is quite simple: we need to make a configuration change to the configuration code of the service and apply an attribute on the service methods.
We'll create a small sample service project and expose the service as a REST endpoint. To do so, create a new empty ASP.NET web application in Visual Studio 2010 and name it OfficeSupplies
. Within the created web application, add a new WCF service called TonerService
. This triggers the creation of both the service interface, ITonerService.cs
, and the service implementation, TonerService.cs
.
To allow our service to communicate using REST, we'll first create a REST endpoint. In the web.config
file, we'll start by adding the webHttp
behavior:
<system.serviceModel> <behaviors> ... <endpointBehaviors> <behavior name="webBehavior"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel>
Next, we can add a new endpoint that uses this behavior:
<services> <service name="OfficeSupplies.TonerService"> <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" bindingConfiguration="" contract="OfficeSupplies.ITonerService"/> </service> </services> </system.serviceModel>
Finally, we have to apply an attribute, WebGetAttribute
, on the service methods we want to expose over REST. Using the UriTemplate
on this attribute, we can use the same endpoint for several service methods. In the following sample code snippet, we can see that IsTonerAvailable
has its UriTemplate
set to Toner:
[OperationContract] [WebGet(UriTemplate = "toner", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml)] bool IsTonerAvailable();
This service method can thus be accessed using http://localhost:123/TonerService.svc/Toner.
If we want to pass in a parameter, we can do so using a query expression. If we want to check the toner for a specific color, we can pass the color in using the following method:
[OperationContract] [WebGet(UriTemplate = "toner/{color}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml)] bool IsColorAvailable(string color);
To invoke this service, we can perform a call to http://localhost:123/TonerService.svc/Toner/Red.