WCF is the Microsoft framework for building applications that communicate over network using different protocols. WCF allows the developers to build distributed applications using SOAP. WCF also had the ability to expose and consume REST services.This post explains how to build REST service using WCF.
Note: To build REST Service new infrastructure was added to WCF in .NET Framework 3.5 in the System.ServiceModel.Web assembly.
The two new attributes added to this programming model are
You can read REST Overview before building the RESTful service.
URI Template which enables you to declare the URI and Verb to each method.
WebHttpBinding and WebHttpBehavior provide the correct networking stack for using REST. WebServiceHost and ServiceHostFactory provides information about hosting infrastructure.
WCF routing message is based on the concept of action. Each action is mapped to a particular method to dispatch the message.The value of action is based on method name or namespace of service or Action property of OperationContract attribute.
When you use the REST with WCF, the dispatching of message is not based on action it is based on URI of the incoming request and HTTP verb being used. Implementing the RESTful endpoint.
The WCFREST service contract definition looks like
WebGetAttribute tells the dispatcher that method should respond to HTTP GET Requests.WebInvokeAttribute is mapped to HTTP POST by default. UriTemplate can be used to customize the URI and HTTP verb.
WebHttpBehavior,WebHttpBinding objects can be used to create a REST endpoint.
We can also do the Endpoint configuration using Web.Config file as folllows
Self-hosting end points
In WCF Hosting Scenario it requires an .svc file inside Internet Information Services(IIS) which points to the service type, plus entries in the web.config file to inform WCF about the endpoint.
In REST endpoints hosting Microsoft added WebServiceHostFactory , which frees you from configuration of endpoint. The RESTful service .svc file looks like
WebServiceHostFactory creates an instance of the WebServiceHost and auto-configure the end-point using WebHttpBinding and WebHttpBehavior. We don’t need to do any configuration in Web.config file.
However for customizing the binding we need to add the appropriate entries in the configuration file. It looks like
The above configuration file using HTTP basic authentication on service endpoint. Once the service is up and running you can hit the root URI with any client.
We have learned the basic WCF features that enable us to build the REST Architectural style service.
|Share this post :|