In this article we will create a WCF Data Service that takes $JSONP in a query and returns JSON data as a response. For example if we want to fetch data as JSON we can fetch as the following:
http://localhost:5157/WcfDataService1.svc/People?$format=json
To start with, let us create a WCF Data Service on a School Database. Open Visual Studio 2010 as an administrator and create a Web Application. We will be hosting a WCF Data Service in a web application.
Create DataModel
We will create a DataModel using the ADO.Net Entity framework. To add a DataModel we need to add an ADO.Net Entity Model from the Data Tab.
We want to create a DataModel from a database, so we will be choosing Generate from the database option.
After this we need to choose the Server name and database name. You can select an appropriate authentication mechanism, in my case I am choosing Windows Authentication.
In the last step, we need to select the tables and views that we want to keep as part of the DataModel. In this case I am selecting all the tables.
Create WCF Data Service
To create a WCF Data Service, add a new item, selecting the WCF Data Service project template from the Web Tab:
Modify WcfDataService.svc.cs as follows. We need to provide a DataModel name. In this case the DataModel is SchoolEntites that we created previously.
By this step we have created a WCF Data Service on SchoolEntities DataModel. Now press F5 to host the created WCF Data Service in the Cassini server and query in the browser.
And we can query a particular set of entities as in the following:
Enabling JSONP and URL Control Format
Read More Detail Here MSDN
If we want to fetch a response in JSON format as follows:
http://localhost:5157/WcfDataService1.svc/People?$format=json
We will get the following exception:
JSONP is used to fetch data from the client side eventhough the request needs to be cross-domain. To support $JSONP, we need to intercept the message before it gets dispatched. Upon interception:
- Read the request URL and if $JSONP is there remove it from the querystring. Because reading $JSONP in a WCF Data Service connection string during runtime will throw an exception as shown above.
- And change Accept header to application/json
To enable this you need to add the following file JSONPSupportBehavior.cs. Download the sample project and file from the MSDN Code Gallery .
Extract the downloaded ZIP file and select JSONSupportBehavior.cs. Right-click on your project and add the existing item. Choose the file JSONSupportBehavior.cs and add it to the project.
Then modify WcfDataService.svc.cs as follows:
We need to include the JSONPSupportBehavior service attribute. Now go ahead and press F5 to run and fetch people in the JSON format as follows:
http://localhost:5157/WcfDataService1.svc/People?$format=json
In this way we can enable the $JSONP format on the WCF Data Service. I hope this article is useful. Thanks for reading.