ASP. NET Web API 2 Getting Started tutorial

Source: Internet
Author: User

Translator: jiankunking Source: http://blog.csdn.net/jiankunking

SOURCE download

HTTP not only provides Web page services, it is also a powerful platform for building public services and data APIs. HTTP is simple, flexible, and ubiquitous. Almost all of the platforms you can think of have an HTTP library, so the HTTP service can affect 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 based on the. In this tutorial, you will use the ASP. NET Web API to create a Web API and return a list of products.

Development tools and environment versions in this tutorial:

    • Visual Studio Update 2
    • Web API 2
Create a Web API project

In this tutorial, you will use the ASP. NET Web API to create a Web API project that returns a list of products. The front-end Web page uses jquery to display the results.

Start Visual Studio, choose New New Project from the Start screen or choose from the File menu: New-Project.

On the template page select: Installed-Template-visual c#-web.
In the list of project templates, select the Asp.netweb application.
Project name: "Productsapp" and click "OK".

In the Create new ASP. NET Project dialog box, select an empty template. To add a folder and a core reference to the following, select: Web API. Click OK.

You can also use the Web API template to create a Web API project.
The Web API template uses ASP. NET MVC to provide the API help page. In this tutorial I used an empty template because I didn't want to use MVC to demonstrate the Web API. In general, you do not need to know ASP. NET MVC with the MVC Web API.

Add model

A model is an object that represents data in an application. The ASP. NET Web API can automatically serialize your model to json,xml or other formats, and then populate the serialized data into the HTTP response message body.
As long as the client can read the serialization format, it can deserialize the object. Most clients are able to parse XML or JSON. In addition, the client can declare that it wants to communicate through the Accept header format of the HTTP request (that is, the Web API supports format negotiation, and the client can notify the server of the desired format via the Accept header).
Let's create a simple model that represents a product.
If Solution Explorer is not already visible, click the View menu and choose Solution Explorer.

In Solution Explorer, right-click the Models folder. From the context menu, choose Add and then select Class:

Name the class: Product and 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 an object that handles HTTP requests. We will add a controller that can return a product list or a single product with a specified ID.

If you have previously used ASP. NET MVC, then you should already be familiar with the controller. The WEB API controller is similar to an MVC controller, but inherits the Apicontroller class instead of the controller class.

In Solution Explorer, right-click the Controllers folder. Select Add and select Controller.

In the Add Scaffolding dialog box, select Web API controller-empty. Click Add.

Then add the Controller interface, enter: ProductsController, click Add:

You do not need to add your controller to a folder named Controller. The name of the folder is just for the convenience of organizing your source files.

If the file is not open, double-click the file to open it. Replace the code in the file with the following code:

usingProductsapp. Models;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Http;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}};//GET api/products         PublicIenumerable<product>getallproducts()        {returnProducts }//GET api/products/id         PublicIhttpactionresultgetproduct(intID) {varProduct = products. FirstOrDefault (p) = P.id = = Id);if(Product = =NULL)            {returnNotFound (); }returnOk (product); }    }}

To make the sample as simple as possible, the product is stored within a fixed array of controller classes. Of course, in a real application, you will query the database or use some other external data source.
The Controller defines two methods that return a product:

    • The Getallproducts method returns the entire product of the IEnumerable type.
    • The GetProduct method returns a single product based on the ID.

Each method on the controller corresponds to one or more URIs:

Controller Method URI
Getallproducts /api/products
GetProduct /api/products/id

For more information about how to route HTTP requests to the Controller method using the Web API, see ASP.

Expand:
The four main methods of HTTP (GET, PUT, POST, DELETE) are mapped to curd operations in the following ways:

    • Get is used to obtain the presentation of the URI resource, and the get operation should not have any effect on the server;
    • Put is used to update a resource on a URI, and a put can be used to create a new resource if the server allows it;
    • POST is used to create a new resource, and the server creates an object on the specified URI, returning the address of the new resource as part of the response message;
    • Delete is used to delete the specified URI resource.
Invoking the Web API through JavaScript and jquery

In this section, we will add an HTML page that uses AJAX to invoke the Web API. We'll use jquery's Ajax calls to make and update the results page.
In Solution Explorer, right-click the project and select Add, and then select New Item.

In the Add New Item dialog box, select the Web node under the Visual C # node, and then select the HTML page item. The new name is "index." HTML "page.

The index. The contents of the HTML file are replaced by 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 example, I used Microsoft's Ajax CDN. You can also download it from http://jquery.com/, and jquery is also included in the ASP. NET "Web API" project template.

Get Product List

Send an HTTP GET request to "/api/products" to get a list of products.

The JQuery Getjson function sends an AJAX request. In response to an array containing JSON objects. The done function hangs a callback when a request succeeds. Update the DOM with product information in the callback function.

$(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 Products by ID

Get the product by sending an HTTP GET request to "/API/PRODUCTS/ID" (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 call Getjson to send AJAX requests, but this time we stitch the ID into the request URI. The response to the request is a JSON-represented product.

Running the application

Press F5 to start the application debugging. The webpage should look like this:

Get the product by Product ID, enter the ID and click Search:

If you enter an invalid ID, the server will return an HTTP error:

Expand:

For each Http message, the ASP. NET Web API framework determines, through the routing table, which controller handles the request. When you create a new Web API project, it will include a default route like this:

/api/{controller}/{id}

{Controller} and {ID} are two placeholders that, when encountered with a URI that conforms to this style, will begin to look for the appropriate controller method to make the call, with the following rules:

    • {Controller} is used to match the names of controllers;
    • The HTTP request method is used to match the method name; (This rule applies only to GET, POST, PUT, and DELETE)
    • {ID}, if any, will be used to match the ID parameter of the method;
View HTTP requests and responses

The original is an example of IE explained, here in Mozilla Firefox browser to explain.
Now go back to the webpage and press F5 to refresh the page. Mozilla Firefox will capture HTTP traffic between the browser and the Web server. The overview view shows all network traffic for a page:

If you click on the "JSON" tab, you can see how the list of products is serialized into JSON.

Original address

First contact with the Web API, translation of foreign articles, if there is a wrong place, trouble treatise.

Translator: jiankunking Source: http://blog.csdn.net/jiankunking

ASP. WEB API Official documentation

ASP. NET Web API 2 Getting Started tutorial

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.