【ASP.NET Web API教程】1.1 第一个ASP.NET Web API

发布时间:2017-5-27 23:32:41 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"【ASP.NET Web API教程】1.1 第一个ASP.NET Web API ",主要涉及到【ASP.NET Web API教程】1.1 第一个ASP.NET Web API 方面的内容,对于【ASP.NET Web API教程】1.1 第一个ASP.NET Web API 感兴趣的同学可以参考一下。

【ASP.NET Web API教程】1.1 第一个ASP.NET Web API

Your First ASP.NET Web API (C#)
第一个ASP.NET Web API(C#)

By Mike Wasson|January 21, 2012
作者:Mike Wasson | 日期:2012-1-21

本文引自:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.
HTTP不仅服务于web页面。它也是建立暴露服务与数据的API(应用程序编程接口)的功能强大的平台。HTTP简单、灵活且无处不在。几乎你所能想到的任何平台都有一个HTTP库,因此,HTTP服务能够到达范围广泛的客户端,包括浏览器、移动设备、以及传统的桌面应用程序。

ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. In this tutorial, you will use ASP.NET Web API to create a web API that returns a list of products. The front-end web page uses jQuery to display the results.
ASP.NET Web API是一个用来在.NET框架上建立web API的框架。在本教程中,你将运用ASP.NET Web API来创建一个返回产品列表的web API。前端web页面使用jQuery来显示其结果(如图1所示)。

WebAPI1-1

图1. 应用程序的web页面

Download the completed project.
下载完整的项目

This tutorial requires Visual Studio with ASP.NET MVC 4. You can use any of the following:
本教程需要安装有ASP.NET MVC 4的Visual Studio。你可以使用以下任何一个:

  • Visual Studio 2012
  • Visual Studio Express 2012 for Web
  • Visual Studio 2010 with ASP.NET MVC 4 installed.(安装了ASP.NET MVC 4的VS 2010)
  • Visual Web Developer 2010 Express with ASP.NET MVC 4 installed.(安装了ASP.NET MVC 4的VS 2010 Web开发者简装版)

If you are using Visual Studio 2010 or Visual Web Developer 2010 Express, you will need to install ASP.NET MVC 4 separately. The screenshots in this tutorial show Visual Studio Express 2012 for Web.
如果使用Visual Studio 2010或Visual Web Developer 2010 Express,需要独立安装ASP.NET MVC 4。本教程中的屏幕截图显示的是Visual Studio Express 2012 for Web。

Create a Web API Project
创建Web API项目

Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project.
启动Viusal Studio,并从“开始”页面选择“新项目”。或者,从“文件”菜单选择“新建”,然后选择“项目”。

In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET MVC 4 Web Application. Name the project "HelloWebAPI" and click OK.
在“模板”面板中选择“已安装模板”,并展开“Visual C#”节点。在“Visual C#”下选择“Web”。在项目模板列表中选择“ASP.NET MVC 4 Web应用程序”。将该项目命名为“HelloWebAPI”,点击“OK”(如图2所示)。

WebAPI1-2

图2. 创建项目

In the New ASP.NET MVC 4 Project dialog, select Web API and click OK.
在“新ASP.NET MVC 4项目”对话框中,选择“Web API”并点击“OK”(如图3所示)。

WebAPI1-3

图3. 选择Web API项目模板

Adding a Model
添加一个模型

A model is an object that represents the data in your application. ASP.NET Web API can automatically serialize your model to JSON, XML, or some other format, and then write the serialized data into the body of the HTTP response message. As long as a client can read the serialization format, it can deserialize the object. Most clients can parse either XML or JSON. Moreover, the client can indicate which format it wants by setting the Accept header in the HTTP request message.
模型是表示应用程序数据的一种对象。ASP.NET Web API可以自动地把模型序列化成JSON、XML、或某些其它格式,然后这些序列化数据写到HTTP响应的消息体中。只要一个客户端能够读取这种序列化格式,它就可以对这种对象进行反序列化。大多数客户端都能够解析XML或JSON。另一方面,通过设置HTTP请求消息中的Accept报头,客户端能够指示它所希望的是哪一种格式。

Let's start by creating a simple model that represents a product.
我们从创建一个表示产品的简单模型开始。

If Solution Explorer is not already visible, click the View menu and select Solution Explorer. In Solution Explorer, right-click the Models folder. From the context menu, select Add then select Class.
如果“解决方案资源管理器”还不可见,点击“视图”菜单,选择“解决方案资源管理器”。在“解决方案资源管理器”中,右击“模型”文件夹。从上下文菜单选择“添加” — “类”(如图4所示)。

WebAPI1-4

图4. 添加模型

Name the class "Product". Next, add the following properties to the Product class.
将这个类命名为“Product”。下一步,将以下属性添加到这个Product类。

namespace HelloWebAPI.Models{    public class Product    {        public int Id { get; set; }        public string Name { get; set; }        public string Category { get; set; }        public decimal Price { get; set; }    }}

Adding a Controller
添加控制器

A controller is an object that handles HTTP requestst. The New Project wizard created two controllers for you when it created the project. To see them, expand the Controllers folder in Solution Explorer.
控制器是一种处理HTTP请求的对象。“新项目”向导在创建该项目时为你创建了两个控制器。要看到它们,在“解决方案资源管理器”中展开Controllers文件夹。

  • HomeController is a traditional ASP.NET MVC controller. It is responsible for serving HTML pages for the site, and is not directly related to Web API.
    HomeController是传统的ASP.NET MVC控制器。它负责对网站的HTML页面进行服务,且与Web API无直接关系。
  • ValuesController is an example WebAPI controller.
    ValuesController是一个例子型的WebAPI控制器。

Note If you have worked with ASP.NET MVC, then you are already familiar with controllers. They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class. The first major difference you will notice is that actions on Web API controllers do not return views, they return data.
注:如果曾使用过ASP.NET MVC,对控制器已有所熟悉。Web API中的控制器是类似的,只不过它们派生于ApiController类,而不是Controller类。你要注意到的第一个主要区别是Web API控制器上的动作并不返回视图,而返回的是数据。

Go ahead and delete ValuesController, by right-clicking the file in Solution Explorer and selecting Delete.
继续并删除ValuesController,在“解决方案资源管理器”右击此文件,并选择“删除”。

Add a new controller, as follows: 
按以下说明添加一个新控制器:

In Solution Explorer, right-click the the Controllers folder. Select Add and then select Controller.
在“解决方案资源管理器”中右击Controllers文件夹。选择“添加”,然后选择“控制器”(如图5所示)。

WebAPI1-5

图5. 添加一个新的控制器

In the Add Controller wizard, name the controller "ProductsController". In the Template drop-down list, select Empty API Controller. Then click Add.
在“添加控制器”向导中,命名此控制器为“ProductsController”。在“模板”下拉列表中选择“空的API控制器”,然后点击“添加”(如图6所示)。

WebAPI1-6

图6. 创建一个API控制器

The Add Controller wizard will create a file named ProductsController.cs in the Controllers folder.
“添加控制器”向导将在Controllers文件夹中创建一个名为ProductsController.cs的文件。

It is not necessary to put your contollers into a folder named Controllers. The folder name is not important; it is simply a convenient way to organize your source files.
把你的控制器放在名称为Controllers的文件夹中并不是必须的。文件夹名称并不重要,这只是组织你源文件的一种简单约定。

If this file is not open already, double-click the file to open it. Add the following implementation:
如果此文件尚未打开,双击该文件打开它。添加以下代码:

namespace HelloWebAPI.Controllers{    using HelloWebAPI.Models;    using System;    using System.Collections.Generic;    using System.Linq;    using System.Net;    using System.Net.Http;    using System.Web.Http;    public class ProductsController : ApiController    {        Product[] products = new Product[]         {             new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },             new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },             new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }         };        public IEnumerable<Product> GetAllProducts()        {            return products;        }        public Product GetProductById(int id)        {            var product = products.FirstOrDefault((p) => p.Id == id);            if (product == null)            {                throw new HttpResponseException(HttpStatusCode.NotFound);            }            return product;        }        public IEnumerable<Product> GetProductsByCategory(string category)        {            return products.Where(                (p) => string.Equals(p.Category, category,                    StringComparison.OrdinalIgnoreCase));        }    }}

To keep the example simple, products are stored in a fixed array inside the controller class. Of course, in a real application, you would query a database or use some other external data source.
为了保持示例简单,产品被存储在该控制器类的一个固定数组中。当然,在一个实际应用程序中,你会查询一个数据库,或使用某些其它外部数据源。

The controller defines three methods that return either single products or lists of products:
该控制器定义了三个方法,它们或者返回一个单一产品,或一个产品列表:

  • The GetAllProducts method returns the entire list of products as an IEnumerable<Product> type.
    GetAllProducts方法以IEnumerable<Product>类型返回产品的完整列表。
  • The GetProductById method looks up a single product by its ID.
    GetProductById方法通过ID查询一个单一产品
  • The GetProductsByCategory method returns all products with a specified category.
    GetProductsByCategory方法返回指定类别的全部产品。

That's it! You have a working web API. Each method on the controller maps to a URI:
好了,你有了一个能工作的Web API了。该控制器上的每个方法都映射到一个URI(如表1所示):

表1. 控制器方法所映射的URI
Controller Method
控制器方法
URI
GetAllProducts/api/products
GetProductById/api/products/id
GetProductsByCategory/api/products/?category=category

A client can invoke the method by sending an HTTP GET request to the URI. Later, we'll look at how this mapping is done. But first, let's try it out.
客户端可以通过发送一个HTTP的GET请求到这些URI来调用一个方法。稍后,我们将考查这种映射是如何完成的。但首先,让我们先试一试它。

Calling the Web API from the Browser
从浏览器调用Web API

You can use any HTTP client to invoke your web API. In fact, you can call it directly from a web browser.
你可以用任何HTTP客户端来调用你的web API。事实上,你可以直接从一个web浏览器来调用它。

In Visual Studio, choose Start Debugging from the Debug menu, or use the F5 keyboard shortcut. The ASP.NET Development Server will start, and a notification will appear in the bottom corner of the screen showing the port number that it is running under. By default, the Development Server chooses a random port number.
在Visual Studio中,从“调试”菜单选择“启动调试”,或使用F5快捷键。ASP.NET开发服务器(ASP.NET Development Server)将启动,屏幕的右下角部将出现一个通知,显示它运行的端口号。默认地,开发服务器选择随机端口号。

Visual Studio will then automatically open a browser window whose URL points to http//www.localhost:xxxx/, where xxxx is the port number. The home page should look like the following:
Visual Studio然后将自动打开浏览器窗口,其URL指向http//www.localhost:xxxx/,这里,xxxx是端口号。首页看上去应当像这样(如图7所示):

WebAPI1-7

图7. 应用程序首页

This home page is an ASP.NET MVC view, returned by the HomeController class. To invoke the web API, we must use one of the URIs listed previously. For example, to get the list of all products, browse to http://localhost:xxxx/api/products/. (Replace "xxxx" with the actual port number.)
该首页是一个ASP.NET MVC视图,它是由HomeControllers类返回的。为了调用Web API,我们必须使用前面列出的URI之一。例如,要得到全部产品列表,浏览http://localhost:xxxx/api/products/。

The exact result depends on which web browser you are using. Internet Explorer will prompt you to open or save a "file" named products.
确切的结果取决于你所使用的浏览器。Internet Explorer(IE浏览器)将提示你是否打开或保存一个名称为products的“文件”(如图8所示)。

WebAPI1-8

图8. IE的屏幕提示

This "file" is actually just the body of the HTTP response. Click Open. In the Open with dialog, select Notepad. Click OK, and when prompted, click Open. The file should contain a JSON representation of the array of products:
这个“文件”实际只是HTTP的响应体。点击“打开”按钮,在“打开”对话框中选择Notepad(记事本),点击“OK”,并在提示出现时点击“打开”。该文件应当包含产品数组的一个JSON表达:

[{"Id":1,"Name":"Tomato