Getting started with the Web API series Tutorial 1.1-asp.net Web API

Source: Internet
Author: User

Preface

HTTP does more than just serve Web pages. At the same time, it is also a powerful platform for building APIs that expose services and data. HTTP has a simple, flexible, and ubiquitous feature. You can think of almost all platforms include an HTTP library. So HTTP services can be used across 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 on the. NET framework. In this tutorial, you will use the ASP. NET Web API to create a Web API that returns a list of products.

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 and select New Project on the start page. Or select New under the file directory. then select Project.

In the template panel, select installed Templates. then expand the Visual C # node.

Under the Visual C # node. Select Web.

In the list of project templates. Select the ASP. NET WEB application.

Name the item "Productsapp" and click OK.

In the new ASP. NET Project dialog box, select the empty template. In "Add folders and core references for", select the Web API. Click OK.

Gaze: You can also use the Web API template to create Web APIs.

The Web API template uses ASP. NET MVC to provide a help page for the API. I used the empty template in this tutorial because I wanted to show the web API without MVC. In general, you do not have to understand ASP. NET MVC can use the Web API.

Add Model

A model is an object that represents data in your application.

The ASP. NET Web API is capable of serializing your model to JSON, XML, or other formats on its own initiative. It then writes its serialized data to the body of the HTTP response message.

Only if the client is able to read the serialization format, it can deserialize the object.

Almost all client can parse XML or JSON. And. The client can also indicate the format it wants by setting it in the Accept header of the HTTP request.

Let's create a simple model that represents a product.

Assuming the Solution Explorer is not displayed, click the View menu and select Solution Explorer. In the Solution Explorer. Right-click the models directory. Select Add from the context menu. then select Class.

Name the Class "Product". Add the following attribute to the product class.

namespace ProductsApp.Models{    publicclass Product    {        publicintgetset; }        publicstringgetset; }        publicstringgetset; }        publicdecimalgetset; }    }}
Join the Controller

In the Web API, the controller is the object that handles HTTP requests.

We will add a controller that can return multiple or one products based on the ID.

Note: If you have not used ASP. NET MVC, you should already be familiar with the controller. The controller of the Web API is very similar to the MVC controller. But it inherits the Apicontroller rather than the controller.

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

In the Add Scaffold dialog box, select Web API controller–empty.

Click Add.

In the Add Controller dialog box, name the controller "ProductsController".

Click Add.

Next, you will create a file named ProductsController.cs in the Controllers directory.

Note: In fact you do not have to add the controller to the Controllers directory. The directory name is just to make it easier for you to organize your source files.

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

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

To make the demo sample simple, products are stored in a fixed array in the Controller class. Of course, in a real application, you might want to query the database or use a different external data source.

The controller defines two ways to return a product:
1. The Getallproducts method returns the entire product list as a IEnumerable type.
2. The GetProduct method uses its ID to find a single product.

Yes, you already have a Web API that you can use. Each method on the controller corresponds to one or more URIs:

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

For the GetProduct method, the ID in the URI is a placeholder. Like what. To get a product with an ID of 5, the URI is API/PRODUCTS/5.

using JavaScript and jquery to invoke the Web API

In this section, we will add an HTML page that uses AJAX to invoke the Web API. We will use jquery to generate AJAX calls and to update the page with the results returned.

In the Solution Explorer, right-click the project and select Add, then select New Item.

In the Add New Item dialog box, select the Web node under Visual C #, and then select the HTML page option.

The named page is "Index.html".

Replace all of the files with the following 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 case, I'm using a Microsoft Ajax CDN. You can also download it in http://jquery.com/. Let the ASP. NET "Web API" project include jquery.

Get the Product list

To get a list of products. The ability to send a GET request for an HTTP to "/api/products".

The Getjson function of jquery sends Ajax requests.

This includes an array of JSON objects. The Done function specifies a callback that is triggered when the request succeeds. In the callback. We update the DOM with product information.

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

Assuming that you want to get the product by ID, you can send an HTTP GET request to "/api/products/id", where the 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 use Getjson to send AJAX requests, but this time we put the ID in the URI request. Its response will be a JSON object that represents a single product.

Executing the application

Press F5 to start debugging the application, and the Web page will look like this:

In order to get the product by ID, enter the ID and click Search.

Assuming you enter an invalid ID, the server returns an HTTP error message.

using F12 to view HTTP requests and Responses

When you work with HTTP services, it is very helpful to assume that you can see the specifics of HTTP requests and responses.

You can use the F12 developer tools in IE9 to do these things. In IE9, press F12 to open the tool. Click the Network panel and click Start Capturing. Now go back to the Web page and press F5 to load the Web page again.

IE will capture the HTTP transmission between the browser and the webserver. Shows all HTTP transports for a page.

Navigates to the relative URI "api/products/". Select and click Go to Detailed View.

In the concrete view, there are multiple panels for viewing the header and body of the request and response.

Like what. If you click Request headers, you will see the client request "Application/json" in the Accept header.

If you click on the response body, you will see how the product list is serialized into JSON. Other browsers also have similar functionality. Another useful tool is Fiddler, which is a Web debugging proxy tool. You can use Fiddler to view HTTP transmissions, as well as to synthesize HTTP requests, which give you complete control over the HTTP headers on the request.

Getting started with the Web API series Tutorial 1.1-asp.net Web API

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.