001. Start using ASP. 2 (one)

Source: Internet
Author: User

PS: The article just talks about some of the steps and a simple example of how to create a Web API that doesn't involve routing and method selection, and continues with an expert talk about this. Two are translated together, actually two should be together, but together will be very long, on Saturday, this is my review of the translation of the article. )

1. Preface

HTTP is not only dedicated to the Web site, it is also a powerful platform for serving and displaying the evidence. HTTP is simple, spiritual, and ubiquitous. Most of the platforms that can be thought of are http-like, so HTTP services can be used in the browser-side, mobile and desktop applications such as the ubiquitous client. The ASP. NET Web API is a technology that can be provided by the. Nets framework, and in this tutorial you will use the ASP. Web API to create an API to return to the product list.

2. Building API Engineering

In this tutorial, you'll use the ASP. NET Web API to create an API that returns a list of products. First on the front page, use jquery to show the results. The following images

Open VS, select New Web API project. Depending on the different VS version, the new method may be somewhat different, but Datong small differences, you can create their own.

3. Add a digital model

A model is a representation of your numbers in the program. The ASP. NET Web API can automatically serialize your model to JSON, XML, or other formats, and then write these serialized numbers into the HTTP report message. Until the client can read the serialized numbers, it can deserialize the image. Most customers have this capability. In addition, by setting the request in the report message, the head can return the required numbers for the client. (PS: A simple example article, some concepts can also be temperature therefore know prajna new, such as serialization and deserialization)

Let's start by building a simple model to represent a product.

The file is named product and adds the following to the product category

1 namespace Productsapp.models 2 {3 Public     class Product 4     {5 public         int Id {get; set;} 6 public         Strin G Name {get; set;} 7 public         string Category {get, set;} 8 public         decimal price {get; set;} 9     }10}

4. Add an API Controller

In the Web API, the controller is the image of the HTTP request, and we will add a controller that returns the product information through the product ID.

(PS: According to step, the original picture is a lot of screenshots, you can use less to use it)

Named ProductsController, the code is as follows

namespace productsapp.controllers{public    class Productscontroller:controller    {        product[] products = new Product[]         {             new product{id = 1, Name = "Tomato Soup", Category = "groceries", Price = 1},            new product{id = 2, Name = "Tomato Soup", category = "groceries", Price = 1},            new product{id = 3, name = "Tomato Soup", category = "grocer ies ", Price = 1}        ;        Public ienumerable<product> getallproducts ()        {            return products;        }        Public Ihttpactionresult getproduct (int id)        {            var product = products. FirstOrDefault (p) = P.id = = Id);            if (product = null)            {                return httpfound ();            }            return Ok (product);}}}    

In order to keep the case simple, the product is stored in a closed number in this controller, while in the real program, you can access the numbers from the repository or from other paths in the process.

In the controller, two methods are used to return the product.

The Getallproducts method returns a list of products of the ienumerable<product> type

The GetProduct method returns a product through the ID

That's right. We already have the Web API. Each method is visited as follows.

To learn more about how the Web API chooses the controller, you can see the Controller routing option

(PS: Next is this, the above code is actually there is no way, I use vs2012, may not be the Web API 2 of the class, so I can not hit some type, the Internet to find a method, the use of NuGet installed Webapi, but the installation failure, there is known, you can make a table of their own solution. )

5. Show the Numbers

(PS: The static page is still not attached, the main is JS, the author uses jquery)

1 var uri = ' api/products '; 2  3     $ (document). Ready (function () {4       //Send a AJAX request 5       $.getjson (URI) 6           . Done ( Data) {7             //On success, ' data ' contains a list of products. 8             $.each (data, function (key, item) {9               //ADD A List item for the product.10               $ (' <li> ', {Text:formatitem (item)}). AppendTo ($ (' #products '));             12);           });     ), and the     function Formatitem (item) {       return item. Name + ': $ ' + item. price;17     }18     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);     

To get the product list, send a request for "/api/products"

The Getjson method in jquery sends an AJAX request to return the number of numbers that contain the JSON image. The Done method has a callback function, which is executed when the request succeeds.

(This is the ready callback that the DOM completes)

We still use the Getjson method to send requests, but this time put an ID in the URL, then the data will be a product information.

(response is a find function)

(PS: Some of the above knowledge is better understood for me, not to mention everyone, the Saturday night will be a route selection, routing method is quite a rule.) By shallow into the deep, later will look at a deeper layer of the article. )

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.