HTTP is more than just a Web page. It is also a powerful API platform for exposing services and data. HTTP is simple, flexible, and ubiquitous. Almost all of the platforms you can think of will have an HTTP library, so the HTTP service can reach a wide range of clients, including browsers, mobile devices, and traditional desktop applications.
The ASP. NET Web API is a framework for building a Web API based on the. In this tutorial, you will use the ASP. NET Web API to create a Web API that returns a list of products.
The software used in the tutorial is:
Visual Studio 2013
Web API 2
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, create a new project, select the ASP. NET WEB application,
Then select the "Empty" template and check "Web API" in the options under "Core Reference",
You can also use the Web API project template to create a Web API project. The Web API template uses ASP. NET MVC to provide the API help page. This tutorial chose an empty template because I wanted to demonstrate the Web API without using MVC. Generally, using the Web API you don't need to know ASP.
Add model
Model is used to render data in your program. The ASP. NET Web API can automatically serialize your model to JSON, XML, or other format data, and then serialize the data into the body of the HTTP response message. When the client reads the appropriate serialization format, it is able to deserialize the object. Most clients can parse XML or JSON. Also, the client can indicate the data format it needs through the HTTP request header.
Let's start by creating a simple model for rendering a product. In the solution directory, in the models, add a "Product" class:
Public classProduct { Public intId {Get;Set; } Public stringName {Get;Set; } Public stringCategory {Get;Set; } Public decimalPrice {Get;Set; } }
Add a Controller
In the Web API, the controller is used to process HTTP requests. We add a controller to return the product list and return a single product based on the product ID.
Note: If you have already used ASP. NET MVC, you should be familiar with controllers. The controller of the Web API is similar to the MVC controller, but the controller of the Web API inherits from the Apicontroller, and the controller of MVC inherits from the controller.
In the controllers of the solution directory, add a controller, select the scaffolding "Web API 2 Controller-NULL":
The ProductsController code is as follows:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Http;usingSystem.Web.Http;usingProductsapp.models;namespaceproductsapp.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 ; } PublicIhttpactionresult GetProduct (intID) {varProduct = products. FirstOrDefault (p) = P.id = =ID); if(Product = =NULL) { returnNotFound (); } returnOk (product); } }}
Two methods were defined in the controller:
Getallproducts returns the complete list of products, and the URI of this method responds to/api/products;
The GetProduct method returns a single product through the product ID, and the URI of the method response is/api/products/id
To learn more about the controller routing requests for the Web API, refer to the Routing in ASP Web API.
Request a Web API using JavaScript and jquery
Add an HTML page to your project with the following code:
<!DOCTYPE HTML><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head> <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /> <title></title></Head><Body> <Div> <H2>All Products</H2> <ulID= "Products" /> </Div> <Div> <H2>Search by ID</H2> <inputtype= "text"ID= "ProdId"size= "5" /> <inputtype= "button"value= "Search"onclick= "find ();" /> <PID= "Product" /> </Div> <Scriptsrc= "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, the ' data ' contains a list of products.$.each (data,function(key, item) {//ADD A list item for the product. $('<li>', {Text:formatitem (item)}). AppendTo ($ ('#products')); }); }); }); functionFormatitem (item) {returnitem. Name+ ': $' +item. Price; } functionfind () {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>
Get Product List
Send HTTP GET request to "/api/products"
$.getjson (URI) . 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 a single product by ID
Send HTTP GET request to "/API/PRODUCTS/ID"
$.getjson (uri + '/' + ID) . Done (function (data) { $ (' #product '). Text ( Formatitem (data)) . Fail (function (JQXHR, Textstatus, err) { $ (' #product '). Text (' Error: ' + err); });
To run the project:
Finally, you can view the HTTP request and response of the page F12 the developer tool that brings up the browser, or you can use another tool fiddler to view the HTTP request/response.
Note: This article is translated in the original: Getting Started with ASP. NET Web API 2 (C #)
Start the ASP. NET Web API 2 Tour