Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2014-04-15
4
Medium Priority
?
460 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 83

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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
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…
Suggested Courses

824 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