Preface
HTTP not only serves Web pages, but is also a powerful platform for building APIs that expose services and data. HTTP has a simple, flexible, and ubiquitous feature. You can think of. Almost all platforms contain an HTTP library, so HTTP services can be spread across a wide range of clients, including browsers, mobile devices, and traditional desktop applications.
The ASP. NET Web API is a framework for building Web APIs on the. NET framework. In this tutorial, you will use the ASP. NET Web API to create a Web API that returns a list of products.
Create a Web API Project
In this tutorial, you will use the ASP. NET Web API to create a Web API that returns a list of products. The front-end page uses jquery to display the results.
Open Visual Studio and select New Project on the start page. Or, select New in the file directory, and then select Project.
In the template panel, select installed Templates, and then expand the Visual C # node. Under Visual C # nodes, select Web. In the list of project templates, select ASP. NET WEB application. Name the item "Productsapp" and click OK.
In the new ASP. NET Project dialog box, select the empty template. In "Add folders and core references for", select the Web API. Click OK.
Note: You can also use the Web API template to create a Web API. The Web API template uses ASP. NET MVC to provide a help page for the API. I used the empty template in this tutorial because I wanted to show the web API without MVC. In general, you do not have to understand ASP. NET MVC can use the Web API.
Add a model
A model is an object that represents data in your application. The ASP. NET Web API is able to automatically serialize your model into JSON, XML, or other formats, and then write its serialized data to the body of an HTTP response message. As long as the client is able to read the serialization format, it is able to deserialize the object. Almost all clients can parse XML or JSON. Also, the client can specify the format it wants by setting it in the Accept header of the HTTP request.
Let's create a simple model that represents a product.
If Solution Explorer is not displayed, click the View menu and select Solution Explorer. In the Solution Explorer, right-click the Models folder. Select Add from the context menu and select Class.
Name the Class "Product". Add the following properties to the product class.
namespace ProductsApp.Models{ publicclass Product { publicintgetset; } publicstringgetset; } publicstringgetset; } publicdecimalgetset; } }}
Add Controller
In the Web API, the controller is the object that handles HTTP requests. We will add a controller that can return multiple or one products based on the ID.
Note: If you have not used ASP. NET MVC, you should already be familiar with the controller. The controller of the Web API is similar to the MVC controller, but it inherits the Apicontroller rather than the controllers.
In the Solution Explorer, right-click the Controllers folder. Select Add, and then select Controller.
In the Add Scaffold dialog box, select Web API controller–empty. Click Add.
In the Add Controller dialog box, name the controller "ProductsController". Click Add.
Next, you will create a file named ProductsController.cs under the Controllers folder.
Note: In fact you do not have to add the controller to the Controllers folder. The folder name is just to make it easier for you to organize your source files.
If the file is not open, double-click the file to open it. Replace the following code in the file:
usingProductsapp.models;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.web.http;namespace productsapp.controllers{ Public classProductscontroller:apicontroller {product[] products =NewProduct[] {NewProduct {Id =1, Name ="Tomato Soup", Category ="Groceries", Price =1},NewProduct {Id =2, Name ="Yo-Yo", Category ="Toys", Price =3.75M},NewProduct {Id =3, Name ="Hammer", Category ="Hardware", Price =16.99M}}; PublicIenumerable<product>getallproducts() {returnProducts } PublicIhttpactionresultgetproduct(intID) {varProduct = products. FirstOrDefault (p) = P.id = = Id);if(Product = =NULL) {returnNotFound (); }returnOk (product); } }}
To make the example simple, products are stored in a fixed array in the Controller class. Of course, in a real-world application, you might want to query the database or use a different external data source.
The controller defines two ways to return a product:
1. The Getallproducts method returns the entire product list as a IEnumerable type.
2. The GetProduct method uses its ID to find a single product.
Yes, you already have a Web API that you can use. Each method on the controller corresponds to one or more URIs:
Controlle Method |
URI |
Getallproducts |
/api/products |
GetProduct |
/api/products/id |
For the GetProduct method, the ID in the URI is a placeholder. For example, to get a product with an ID of 5, the URI is API/PRODUCTS/5.
using JavaScript and jquery to invoke the Web API
In this section, we will add an HTML page that uses AJAX to invoke the Web API. We will use jquery to generate AJAX calls and to update the page with the results returned.
In the Solution Explorer, right-click the project and select Add, then select New Item.
In the Add New Item dialog box, select the Web node under Visual C #, and then select the HTML page option. The named page is "Index.html".
Replace all of the files with the following code:
<! DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>Product App</title></head><body> <div> <h2>All Products</H2> <ul id="Products" /> </div> <div> <h2>Search by ID</H2> <input type="text" id="ProdId" size= "5" /> <input type="button" value="Search" onclick=" Find (); " /> <p id="Product" /> </div> <script src="Http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js" ></script> <script> varURI =' api/products '; $ (document). Ready ( function () { //Send an AJAX request$.getjson (URI). Done ( function (data) { //On success, ' data ' contains a list of products.$.each (data, function (key, item) { //ADD A list item for the product.$(' <li> ', {Text:formatitem (item)}). AppendTo ($ (' #products ')); }); }); }); function formatitem(item) { returnItem. Name +': $ '+ Item. Price; } function find() { varID = $ (' #prodId '). Val (); $.getjson (URI +'/'+ ID). Done ( function (data) {$(' #product '). Text (Formatitem (data)); }). Fail ( function (JQXHR, Textstatus, err) {$(' #product '). Text (' Error: '+ err); }); }</script></body></html>
There are several ways to get jquery. In this case, I'm using a Microsoft Ajax CDN. You can also download it in http://jquery.com/and let the ASP. NET "Web API" project include jquery.
Get the Product list
In order to get the products list, you can send an HTTP GET request to "/api/products".
The Getjson function of jquery sends Ajax requests. It contains an array of JSON objects. The Done function specifies a callback that is triggered when the request succeeds. In the callback, we update the DOM with product information.
$(document).ready(function () { // Send an AJAX request $.getJSON(apiUrl) .done(function (data) { // On success, ‘data‘ contains a list of products. function (key, item) { // Add a list item for the product. $(‘<li>‘, { text: formatItem(item) }).appendTo($(‘#products‘)); }); });});
get the product by ID
If you want to get the product by ID, you can send a GET request for HTTP to "/api/products/id", where the ID is the product ID.
function find() { var id = $(‘#prodId‘).val(); ‘/‘ + id) .done(function (data) { $(‘#product‘).text(formatItem(data)); }) .fail(function (jqXHR, textStatus, err) { $(‘#product‘).text(‘Error: ‘ + err); });}
We still use Getjson to send AJAX requests, but this time we put the ID in the URI request. Its response will be a JSON object that represents a single product.
running the application
Press F5 to start debugging the application, and the Web page will look like this:
In order to get the product by ID, enter the ID and click Search.
If you enter an invalid ID, the server returns an HTTP error message.
using F12 to view HTTP requests and Responses
When you work with HTTP services, it is helpful to be able to view the details of HTTP requests and responses. You can do this using the F12 Developer tool in IE9. In IE9, press F12 to open the tool. Click the Network panel and click Start Capturing. Now go back to the Web page and press F5 to reload the Web page. IE will capture the HTTP transfer between the browser and the Web server. Shows all HTTP transports for a page.
Navigates to the relative URI "api/products/". Select and click Go to Detailed View. In the detailed view, there are multiple panels for viewing the header and body of the request and response.
For example, if you click Request headers, you will see that the client requested "Application/json" in the Accept header.
If you click on the response body, you will see how the product list is serialized into JSON. Other browsers also have similar features. Another useful tool is Fiddler, which is a Web debugging proxy tool. You can use Fiddler to view HTTP transmissions, or to synthesize HTTP requests, which give you full control over the HTTP header on the request.
Web API 1.1 ASP. NET Web API