Friday, June 22, 2012

JSON Enabled WCF Service using VS2010


The advantages of using JSON enabled WCF service is that the data is communicated in plain text like stream, it does not require any data/message parsing. For exposing a WCF service as JSON enabled WCF service, we need to apply the [WebGet] attribute on the method of the ServiceContract with ResponseFormat as JSON. The binding used here is WebHttpBinding which is also used for REST enable WCF services. While exposing WCF as JSON enable service, the EndPointBehavior for the WCF service is WebHttp which generates JSON response from the WCF service.

Step 1: Open VS2010 and create a new WCF service application, name it as ‘WCF_JSONService’. Open Iservice1.cs and add the following ServiceContract, OperationContract, DataContract. Apply WebGetAttribute on the OperationContract as shown below:



Step 2: Implement the above IService1.cs in the service class:



Step 3: Write the Web.Config file as shown below with ‘WebHttpBinding’ and the ‘EndpointBehavior’:

Step 4: Right click on the WCF service and select properties, select ‘Web’ tab and write the following Url in the ‘Use Local IIS Web Server’:

By using this approach, the WCF service is published on the web Server

Step 5: Open IIS and navigate to the Virtual Directory ‘WCF_JSONService’ created above. Right click on the Service1.Svc and the following result will be displayed:



Now change the url as shown below and hit Enter, the JSON file data will be downloaded as shown below: http://localhost:8081/WCF_JSONService/Service1.svc/Products



Save the file on disc and view it. The data in the response will be similar to the following:

For demo purposes, I am displaying the Data in a notepad. You can always consume it in any client application like Silverlight, as demonstrated here . The advantage of using JSON over REST is, since REST is XML messaging format, it requires parsing. However this is not required in JSON.

No comments:

Post a Comment