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:
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.
Tweet
6 comments:
Thanks for the nice article. One small thing. You mention "Now change the url as shown below and hit Enter, the JSON file data will be downloaded as shown below:" ...but the image shown does not display the url.
ya, I get XML if I hit the endpoint with SoapUI. How do I get JSON?
I have the same problem as the other 2 posters. The URL is missing in the blog and I get XML?
end of URL is /Service1.svc/Products
Really nice! Thanks very much!
How would we change the response format from an array to an object so instead of [{"price":4500,"ProdID":1}] it can be
{"price":4500,"ProdID":1}
Post a Comment