Consume a cross domain hosted WCF webservice using Jquery

Here we will consume a WCF webservice which returns data in JSON format using Jquery.

How to create a WCF is not covered as part of this blog. asuming all the end point configuration and the webservice methods works properly.

Still here you find the end points configuration of the webservice which has to be done in web.config of the webservice.

End Point Configuration

WCFConfig

Highlighted sections should be taken care in the configuration properly.

Service Contract class

Below screen gives the service contract of the method getvalue(string name) using.

ServiceContract

Webservice method

Method

In the above steps we saw configuration detail of the wcf webservice.

To test the webservice copy the url of the webservice and append with the Uri format of the method given in the service contract:

example:

http://localhost:60683/LoggerService.svc/getValue?id=”Prasanta

Note: “Prasanta” is the value which will be passed to the method(getvalue)

When you browse above url, if it downloads some packet of data means the Webserive works properly.

Consume the the webservice using Jquery:

when your application is hosted in another domain and you are trying to consume the webservice hosted in another domain:

Jquery code to fetch the data from the webservice method getValue

JSON

The above code works properly if we consume from the same web application where the webservice is hosted. If it is another domain it gives No transport error as shown below:

ErrorECF

To solve this problem, you need to add $.support.cors = true; inside your javascript before calling the webservice as shown below:

WCFEntrie

Note: Cors stands for Cross-Origin Resource Sharing. making it true solves the cross domain issue

Now the above code can access the web service and returns the data.

Now above code worked properly on Internet explored, why not in Firefox or any other browser. what may be the issue>

While troubleshooting I tried adding a global.asax in my web service solution to find the request from Firefox browser which was giving HttpMethod==”OPTIONS”, instead of “GET” which I am using in web service.

Note: In Internet Explorer, it sends “GET” as HttpMethod.
I made some changes to add the header as “GET” or “POST”, so that web service can understand there is request for GET Method and it will return the value
global3

 

Still there is some issue, We need to allow all the cross domain request by making “Access-Control-Allow-Origin=*” in the web service side as shown below:

global2

 

 

 

Now this web service can be called from any browser:-)

 

 

Thanks,

Prasanta

About Prasanta Barik

Hello
This entry was posted in ASP .Net, WebServices and tagged , , , . Bookmark the permalink.

Leave a comment