Solved

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

Posted on 2014-04-15
4
443 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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
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…

813 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

14 Experts available now in Live!

Get 1:1 Help Now