I am following this tutorial to build my first Asp.net Web API in a Web Form website but I am facing an issue. I have created two projects:
- host project for the definition of the web service
- client project to consume the web
service.
Now my issue is that if I navigate to my web api URL using a web browser ex) http://localhost:39930/api/products/ then this works perfectly and an XML or Json data is returned depending on the browser.
However, if I use the web service URL of the in my client website then nothing get returned!
Here is how I call the web service from my client website:
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody id="products">
</tbody>
</table>
<script type="text/javascript">
function getProducts() {
$.getJSON("http://localhost:39930/api/products",
function (data) {
$('#products').empty(); // Clear the table body.
// Loop through the list of products.
$.each(data, function (key, val) {
// Add a table row for the product.
var row = '<td>' + val.Name + '</td><td>' + val.Price + '</td>';
$('<tr/>', { text: row }) // Append the name.
.appendTo($('#products'));
});
});
}
$(document).ready(getProducts);
</script>
And here is a snapshot of the request in firebug:

Notice that the response is empty.
So, am I doing something wrong here? Is there some configuration that should be added to allow a service to be remotely called?
Thanks in advance.
It is because your host project and client project are running on different ports which is violating the same origin policy and its prohibited. See the details here http://en.wikipedia.org/wiki/Same_origin_policy
If you want this to work, you can use jsonp instead of json. Have a look at this article http://www.jquery4u.com/json/jsonp-examples/#.UISVAo3iYsc