Original: Getting Started with ASP. NET Web API 2
Step 1: Create a new Empty Web API Project.
Step 2: Add a Model:
Public classProduct { Public intId {Get;Set; } Public stringName {Get;Set; } Public stringCategory {Get;Set; } Public decimalPrice {Get;Set; } }
Step 3: Add an empty Web API Controller:
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); } }
At this point we have completed a Web API. Create a new HTML page to invoke this web API:
<!DOCTYPE HTML><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head> <title>Product App</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>
To see the effect:
Translation ASP. NET Web API 2 Getting Started