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