Objective
HTTP does more than just serve Web Pages. It is also a powerful platform for creating APIs that showcase services and data. HTTP is simple, flexible, and ubiquitous. You can imagine that almost any platform will have an HTTP service library. HTTP services can involve a wide range of clients, including browsers, various mobile devices, and traditional desktop applications.
The ASP. Net Web API is a framework that is used to build Web APIs on the. Net Framework framework. In this tutorial, you will use the ASP. NET Web API framework to create a Web API that returns a list of products. The front-end Web page uses jquery to show the results.
In this tutorial I will use VS2013 to create a simple example. Provides sample download link for this article Project http://pan.baidu.com/share/link?shareid=928144769&uk=4244870074
Create a Web API project
The first step: Start Visual Studio and create the project. Here is the project creation process.
You can also create a Web API project that leverages the Web API template. The Web API template uses ASP. NET MVC to provide the help page for the API. I am using an empty template in this tutorial because I want to show the No MVC Web API. In general, you do not need to know that the Web API is used in ASP.
Add model
A model is an object that presents data in your application. The ASP. NET Web API can automatically serialize your model to JSON, XML, or some other format, and then write the data of the serialized session to the body of the HTTP response message. As long as the client can read the serialized data, it can also deserialize the object. Most clients can parse JSON or XML. Additionally, the client can declare the format of the accept header that it wants to set through the HTTP request message.
Let's start by creating a simple model for displaying products.
Right-click in the Model folder, as shown in. Then name it "Product" and add the following attributes to it:
Namespace webapi.models{public class Product {public int Id {get; set} public string Name {get; set;} Public St Ring Category {get; set;} public decimal price {get; set;}} }
Add Controller
In the Web API, the controller is an object that handles HTTP requests. We will add a controller that either returns the list data for a product or returns individual product information through the product ID.
Note: If you are using ASP. NET MVC, you are already familiar with the controller. The Web API controller is similar to an MVC controller, but inherits the Apicontroller class instead of the controller class.
Right-click on the Controller folder and add the controller, then select an empty API controller template as shown in the name ProductsController.
You do not have to put the API controller you added into a folder named "Controller". This is just a handy folder name to organize your source files.
Then open the controller file ProductsController, replacing the code with the following
Using System; Using System.Collections.Generic; Using System.Linq; Using System.Net; Using System.Net.Http; Using System.Web.Http; Using Webapi.models; Namespace webapi.controllers{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);}} }
To keep the sample simple, you can see from the code above that we keep the data in a fixed array variable. Of course, in a real application, you would query a database, or other data source.
Two ways to return a product are defined in the controller:
The getallproducts method returns the entire list of products, with the ienumerable<product> type as the return type.
The Getproductbyid method queries a single product by Product ID.
As simple as this, now you have a working Web API. Each method on the controller corresponds to one or more URIs.
For Getproductbyid methods, the ID in the URI is a placeholder. For example, to obtain a product with an ID of 5, the URI is API/PRODUCTS/5.
For more information about how the WEB API routes HTTP requests to controller methods, see routing in the ASP. NET Web API in this series.
Invoking the Web API through JavaScript and jquery
In this section, we will add an HTML page to use AJAX to invoke the Web API. We'll use jquery's Ajax to invoke and update the results of the page.
On the Web API project, right-select the HTML page to add and name index.
In this document we are directly http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js by using the Microsoft Ajax CDN.
Replace the entire contents of the Index.html file with the following:
<! DOCTYPE html> Getallproducts
In order to obtain a list of products, a "api/products" HTTP GET request needs to be sent.
The Getjson function of jquery sends an AJAX request. In response to an array that contains JSON objects. The specified done function invokes the callback function if the request succeeds. In this callback function, we will update the new product information to the DOM element.
var uri = ' api/products '; $ (document). Ready (function () { $.getjson (URI) . Do (function (data) { $.each (data, function (key, item) { $ (' <li> ', {Text:formatitem (item)}). AppendTo ($ (' #products '));}); function Formatitem (item) {return item. Name + ': $ ' + item. Price; }
GetProduct
With an ID to get information about a product, we need to send an HTTP request for "API/PRODUCTS/ID", the ID is the product ID.
function Find () {var id = $ (' #prodId '). Val (); $.getjson (uri + '/' + 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 request URI. The response from this request is a JSON representation of a single product.
Debug, run
You can see from the above demo that the list is implemented, and then search through the search box below, that is, a single ID to get a single product information is also implemented.
I'm using IE10 now, so you can view the requested information directly through F12.
Summarize
This article initially briefly uses the ASP. NET Web API as a simple getting started example. Through a simple understanding and translation of the Microsoft Official website article, to further learn English, improve their ability to read English articles, but also to learn about Microsoft's new technology, although the Web API came out for a long time, but for me, this is also the first contact. If you are viewing this article, hopefully this article will help you. If there is anything wrong with this article, please understand, and I hope you can help me fix it.
The next section will learn to create a Web API that supports CRUD operations.
The reference link for this article is Http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
ASP. 2 first lesson-Getting Started