Cross-domain Problems in JSON Communication Between ASP.NET Web API 2 and jQuery.ajax()

I had a task to create an ASP.NET web page that should use AJAX request to dynamically update the items of the dropdownlist control SignerDropDownList. I’ve created a javascript function that handles onchange event of the parent dropdownlist. The relevant portion of the script is shown below:

Variable webServiceUrl is a string with URL to web service in MVC format. Just something like “http://host_name:port_number/ws/api/Signer/1”

At first I clear the list of items, then I process the response from the server which comes in the following
JSON format and add items to dropdownlist control.

For the server-side web service I’ve created an Entity Framework model and Web API 2 controller in two projects. The test of the web service from the browser passed.
I successfully publish web service to IIS and assign a port. The test of the ajax call failed due to cross-domain problems.

This problem can be solved very easily by enabling CORS in ASP.NET Web API. All necessary information about that is here

In addition I had to change ajax function on HTML page.

I’ve tested in Google Chrome, everything is OK. But Internet Explorer could not get data from web service. I’ve looked at the Network tab in IE debugger and found that IE did not send any request to web service.

After some time searching in Google I found that JSONP could help to solve this issue. I’ve changed the ajax call and noticed that IE really sent the request. But now it failed due to incorrect format. So I need to change the web service to correctly format the response in JSONP format. This can be done with WebApiContrib.
All information about how to install and use it is located on GitHub here

Beside that we should add a parameter to ajax function to instruct it to make a JSONP call. The final javascript code is listed below:

When I looked at the Netwok tab of IE debugger I saw a request to web sevice.
/ws/api/Signer/1?callback=jQuery1102007129232717448897_1424862016652&_=1424862016653 GET 200 text/javascript 484 B 4.85 s// <![CDATA[
13282 15 4828 16 0 0
// ]]>

So, to organize the AJAX communication between web page and Web API we need an jQuery.ajax() request with relevant paramters on the client side. On the server side we should implement CORS and JSONP support in our web service.

Leave a Reply

Your email address will not be published. Required fields are marked *