Solved

Consume WEB API 2 Service Hosted on IISS 8.0 From Seperate Client App?

Posted on 2014-04-15
4
442 Views
Last Modified: 2014-04-24
Q. How do I consume a .NET Web API 2 RESTful service from a separate client app?

Q. Should the API be hosted to the Internet instead of the Intranet (my current setup)?

I find many API examples having a one VS2010 solution containing twp apps, Web API project and simple asp.net project and HTML page. I've built them and they work on Visual Studio.

I don't find example where a Web API and Client are setup in two very different places.

This I know, I cannot return any data no matter what I do. Help!

1. I have the test Web API 2 hosted on our internal 2012 IIS 8.0 server.
2. I can return browser data like so:
     - http://192.168.1.11:8083/api/products
     - data:
                    [{"Id":1,"Name":"Tomato Soup","Category":"Groceries","Price":1.0},
                     {"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75},
                     {"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}]

I'm found ajax and getJSON don't like cross-domain calls and do NOT return any data:

  <div>
       <h2>All Products</h2>
       <ul id="products" />
  </div>
       
      var uri = 'http://192.168.1.11:8083/api/products';

          $.getJSON(uri)
              .done(function (data) {
                  $.each(data, function (key, item) {                      
                      $('<li>', { text: item.Name + ': $' + item.Price }).appendTo($('#products'));
                  });
              });

I found using JSONP does NOT return any data:

           $.getJSON(uri + '?GetAllProducts=?' )
              .done(function (data) {
                  $.each(data, function (key, item) {                      
                      $('<li>', { text: item.Name + ': $' + item.Price }).appendTo($('#products'));
                  });
              });
0
Comment
Question by:WorknHardr
  • 3
4 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 40002241
Check this : http://api.jquery.com/jquery.getjson/#jsonp
What do your server side code return putting the following address directly in the browser address bar :
http://192.168.1.11:8083/api/products?callback=ABCDEF

To be able to use JSONP your server MUST return something like :

ABCDEF([{"Id":1,"Name":"Tomato Soup","Category":"Groceries","Price":1.0},{"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}]);

I mean : ABCDEF( your JSON DATA HERE )

jQuery will replace ABCDEF by a random function name so your server query the << callback >> parameter to get this random function name (represented by the question mark << ? >>), you don't need to provide this random function name, just use the question mark : callback=?
0
 

Author Comment

by:WorknHardr
ID: 40002477
Using: http://192.168.1.11:8083/api/products?callback=ABCDEF
Returns:  [{"Id":1,"Name":"Tomato Soup","Category":"Groceries","Price":1.0},{"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}]

Using: http://192.168.1.11:8083/api/products?GetAllProducts=?
Returns: [{"Id":1,"Name":"Tomato Soup","Category":"Groceries","Price":1.0},{"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}]

[Api Controller]
public class ProductsController : ApiController
    {
        Product[] products = new Product[]
        {
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
        };

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
    }

[product.cs]
public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
0
 

Accepted Solution

by:
WorknHardr earned 0 total points
ID: 40010793
Solution:
Using Web API 2 (Individual User Account + CORS Enabled) from AngularJS Client
http://www.codeproject.com/Articles/742532/Using-Web-API-Individual-User-Account-plus-CORS-En
0
 

Author Closing Comment

by:WorknHardr
ID: 40019509
thx
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

930 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now