0

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:

  1. host project for the definition of the web service
  2. 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:

enter image description here

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

... And here is a really good article to get this issue resolved: west-wind.com/weblog/posts/2012/Apr/02/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.