Step 1: Open VS2010 and create a blank solution, name it as ‘SL4_Calling_REST_Service_with_JSON’. In this solution, add a new WCF service (targeted to .NET 4.0) and call this project as ‘WCF_REST_Service’. Define the following ServiceContract, OperationContract and DataContract in the IService.cs file.
Note that the GetEmployees() method defines JSON as the request and response format from both sides.
Step 2: Implement the above interface in the Service class as shown below in Service.svc.cs file:
Step 3: Define the Web.Config file as shown below with the addition of protocol mapping for WebHttpBinding and endpoint behavior for WebHttp.
Step 4: Publish the service on the IIS Web Server.
Note: On the Root of the IIS, you must have the clientaccesspolicy.xml file so that Silverlight client can make call to it.
Step 5: In the same solution, add a new Silverlight application and call it ‘SL4_JSON_Client’. Add a reference to System.Json assembly in the application. In MainPage.xaml, add a Button and DataGrid control as shown below and also subscribe to the Click event of the Button :
Step 6: In the MainPage.Xaml.cs, add the Employee class as shown below. This class is used to store the result of the query fired on the result, from the JSON response.
Step 7: Add the following code on the Click event of the ‘Get Employees’ button. This code makes an async call to the WCF REST Service using OpenReadAsync method of the WebClient class, by passing WCF Service URL to it. The OpenReadCompleted event will collect the JSON response from the service and then this result will be processed. The code is as below:
Note: Read the comments carefully.
Step 8: Run the application, the result will be as shown below:
Download the source code
Will you give this article a +1 ? Thanks in advance