Tuesday, November 27, 2012

Your First ASP.NET Web API (C#) - III

In the Add Controller wizard, name the controller "ProductsController". In the Template drop-down list, select Empty API Controller. Then click Add.

The Add Controller wizard will create a file named ProductsController.cs in the Controllers folder.
It is not necessary to put your contollers into a folder named Controllers. The folder name is not important; it is simply a convenient way to organize your source files. 
If this file is not open already, double-click the file to open it. Add the following implementation:
namespace HelloWebAPI.Controllers
{
    using HelloWebAPI.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;

    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 Product GetProductById(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return product;
        }

        public IEnumerable<Product> GetProductsByCategory(string category)
        {
            return products.Where(
                (p) => string.Equals(p.Category, category,
                    StringComparison.OrdinalIgnoreCase));
        }
    }
}
To keep the example simple, products are stored in a fixed array inside the controller class. Of course, in a real application, you would query a database or use some other external data source.
The controller defines three methods that return either single products or lists of products:
  • The GetAllProducts method returns the entire list of products as an IEnumerable<Product> type.
  • The  GetProductById method looks up a single product by its ID.
  • The  GetProductsByCategory method returns all products with a specified category.
That's it! You have a working web API.  Each method on the controller maps to a URI:
Controller Method URI
GetAllProducts /api/products
GetProductById /api/products/id
GetProductsByCategory /api/products/?category=category
A client can invoke the method by sending an HTTP GET request to the URI. Later, we'll look at how this mapping is done. But first, let's try it out.

Calling the Web API from the Browser

You can use any HTTP client to invoke your web API. In fact, you can call it directly from a web browser.
In Visual Studio, choose Start Debugging from the Debug menu, or use the F5 keyboard shortcut.  The ASP.NET Development Server will start, and a notification will appear in the bottom corner of the screen showing the port number that it is running under. By default, the Development Server chooses a random port number.
Visual Studio will then automatically open a browser window whose URL points to http//www.localhost:xxxx/, where xxxx is the port number. The home page should look like the following:

This home page is an ASP.NET MVC view, returned by the HomeController class.  To invoke the web API, we must use one of the URIs listed previously. For example, to get the list of all products, browse to http://localhost:xxxx/api/products/. (Replace "xxxx" with the actual port number.)
The exact result depends on which web browser you are using. Internet Explorer will prompt you to open or save a "file" named products.

This "file" is actually just the body of the HTTP response. Click Open. In the Open with dialog, select Notepad. Click OK, and when prompted, click Open. The file should contain a JSON representation of the array of products:
[{"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}]
Mozilla Firefox, on the other hand, will display the list as XML in the browser.

The reason for the difference is that Internet Explorer and Firefox send different Accept headers, so the web API sends different content types in the response.
Now try browsing to these URIs:
  • http://localhost:xxxx/api/products/1
  • http://localhost:xxxx/api/products?category=hardware
The first should return the entry with ID equal to 1. The second should return a list of all the products with Category equal to "hardware" (in this case, a single item).

Calling the Web API with Javascript and jQuery

In the previous section, we invoked the web API directly from the browser. But most web APIs are meant to be consumed programmatically by a client application. So let's write a simple javascript client.
In Solution Explorer, expand the Views folder, and expand the Home folder under that. You should see a file named Index.cshtml. Double-click this file to open it.

Index.cshtml renders HTML using the Razor view engine. However, we will not use any Razor features in this tutorial, because I want to show how a client can access the service using plain HTML and Javascript. Therefore, go ahead and delete everything in this file, and replace it with the following:
<!DOCTYPE html>
<html lang="en">
<head>
    <title>ASP.NET Web API</title>
    <link href="../../Content/Site.css" rel="stylesheet" />
    <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript">
        // TODO Add script
    </script>
</head>
<body id="body" >
    <div class="main-content">
        <div>
            <h1>All Products</h1>
            <ul id="products"/>
        </div>
        <div>
            <label for="prodId">ID:</label>
            <input type="text" id="prodId" size="5"/>
            <input type="button" value="Search" onclick="find();" />
            <p id="product" />
        </div>
    </div>
</body>
</html>

Getting a List of Products

To get a list of products, send an HTTP GET request to "/api/products". You can do this with jQuery as follows:
<script type="text/javascript">
    $(document).ready(function () {
        // Send an AJAX request
        $.getJSON("api/products/",
        function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, val) {

                // Format the text to display.
                var str = val.Name + ': $' + val.Price;

                // Add a list item for the product.
                $('<li/>', { text: str })    
                .appendTo($('#products'));   
            });
        });
    });
</script>
The getJSON function sends the AJAX request. The response will be an array of JSON objects. The second parameter to getJSON is a callback function that is invoked when the request successfully completes.

Getting a Product By ID

To get a product by ID, send an HTTP GET  request to "/api/products/id", where id is the product ID. Add the following code to the script block:
function find() {
    var id = $('#prodId').val();
    $.getJSON("api/products/" + id,
        function (data) {
            var str = data.Name + ': $' + data.Price;
            $('#product').text(str);
        })
    .fail(
        function (jqXHR, textStatus, err) {
            $('#product').text('Error: ' + err); 
        });
}            
Again, we call the jQuery getJSON function to send the AJAX request, but this time we use the ID to construct the request URI. The response from this request is a JSON representation of a single Product object.
The following code shows the complete Index.cshtml file.
<!DOCTYPE html>
<html lang="en">
<head>
    <title>ASP.NET Web API</title>
    <link href="../../Content/Site.css" rel="stylesheet" />
    <script src="../../Scripts/jquery-1.7.1.min.js" 
        type="text/javascript"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                // Send an AJAX request
                $.getJSON("api/products/",
                function (data) {
                    // On success, 'data' contains a list of products.
                    $.each(data, function (key, val) {

                        // Format the text to display.
                        var str = val.Name + ': $' + val.Price;

                        // Add a list item for the product.
                        $('<li/>', { text: str })
                        .appendTo($('#products'));
                    });
                });
            });

            function find() {
                var id = $('#prodId').val();
                $.getJSON("api/products/" + id,
                    function (data) {
                        var str = data.Name + ': $' + data.Price;
                        $('#product').text(str);
                    })
                .fail(
                    function (jqXHR, textStatus, err) {
                        $('#product').text('Error: ' + err);
                    });
            }
        </script>

</head>
<body id="body" >
    <div class="main-content">
        <div>
            <h1>All Products</h1>
            <ul id="products"/>
        </div>
        <div>
            <label for="prodId">ID:</label>
            <input type="text" id="prodId" size="5"/>
            <input type="button" value="Search" onclick="find();" />
            <p id="product" />
        </div>
    </div>
</body>
</html>

Running the Application

Press F5 to start debugging the application. The web page should look like the following:

It's not the best in web design, but it shows that our HTTP service is working. You can get a product by ID by entering the ID in the text box:

If you enter an invalid ID, the server returns an HTTP error:

Understanding Routing

This section explains briefly how ASP.NET Web API maps URIs to controller methods. For more detail, see Routing in ASP.NET Web API.
For each HTTP message, the ASP.NET Web API framework decides which controller receives the request by consulting a route table. When you create a new Web API project, the project contains a default route that looks like this:
/api/{controller}/{id}
The {controller} and {id} portions are placeholders. When the framework sees a URI that matches this pattern, it looks for a controller method to invoke, as follows:
  • {controller} is matched to the controller name.
  • The HTTP request method is matched to the method name. (This rule applies only to GET, POST, PUT, and DELETE requests.)
  • {id}, if present, is matched to a method parameter named id.
  • Query parameters are matched to parameter names when possible
Here are some example requests, and the action that results from each, given our current implementation.
URI HTTP Method Action
/api/products GET GetAllProducts()
/api/products/1 GET GetProductById(1)
/api/products?category=hardware GET GetProductsByCategory("hardware")
In the first example, "products" matches the controller named ProductsController. The request is a GET request, so the framework looks for a method on ProductsController whose name starts with "Get...". Furthermore, the URI does not contain the optional {id} segment, so the framework looks for a method with no parameters. The ProductsController::GetAllProducts method meets all of these requirements.
The second example is the same, except that the URI contains the {id} portion. Therefore, the frameworks calls GetProduct, which takes a parameter named id. Also, notice that value "5" from the URI is passed in as the value of the id parameter. The framework automatically converts the "5" to an int type, based on the method signature.
Here are some requests that cause routing errors:
URI HTTP Method Action
/api/products/ POST 405 Method Not Allowed
/api/users/ GET 404 Not Found
/api/products/abc GET 400 Bad Request
In the first example, the client sends an HTTP POST request. The framework looks for a method whose name starts with "Post..." However, no such method exists in ProductsController, so the framework returns an HTTP response with status 405, Method Not Allowed.
The request for /api/users fails because there is no controller named UsersController. The request for api/products/abc fails because the URI segment "abc" cannot be converted into the id parameter, which expects an int value.

Using F12 to View the HTTP Request and Response

When you are working with an HTTP service, it can be very useful to see the HTTP request and request messages. You can do this by using the F12 developer tools in Internet Explorer 9. From Internet Explorer 9, press F12 to open the tools. Click the Network tab and press Start Capturing. Now go back to the web page and press F5 to reload the web page. Internet Explorer will capture the HTTP traffic between the browser and the web server. The summary view shows all the network traffic for a page:

Locate the entry for the relative URI “api/products/”. Select this entry and click Go to detailed view. In the detail view, there are tabs to view the request and response headers and bodies. For example, if you click the Request headers tab, you can see that the client requested "application/json" in the Accept header.

If you click the Response body tab, you can see how the product list was serialized to JSON. Other browsers have similar functionality. Another useful tool is Fiddler, a web debugging proxy. You can use Fiddler to view your HTTP traffic, and also to compose HTTP requests, which gives you full control over the HTTP headers in the request.

No comments:

Post a Comment