通过 ASP.NET Web API 生成 RESTful ApiBuild RESTful APIs with ASP.NET Web API

Web 训练营团队使用by Web Camps Team

动手实验:使用 ASP.NET 4.x 中的 Web API 生成联系人管理器应用程序的简单 REST API。Hands on lab: Use Web API in ASP.NET 4.x to build a simple REST API for a contact manager application. 你还将生成一个使用 API 的客户端。You will also build a client to consume the API.

在最近几年中,它已变得清楚: HTTP 并非仅用于提供 HTML 页面。In recent years, it has become clear that HTTP is not just for serving up HTML pages. 它也是一个功能强大的平台,用于生成 Web Api,使用几个谓词 (GET、POST 等) 加上一些简单的概念,如 uri标头It is also a powerful platform for building Web APIs, using a handful of verbs (GET, POST, and so forth) plus a few simple concepts such as URIs and headers. ASP.NET Web API 是一组可简化 HTTP 编程的组件。ASP.NET Web API is a set of components that simplify HTTP programming. 由于它是在 ASP.NET MVC 运行时的基础上构建的,因此 Web API 会自动处理 HTTP 的低级传输细节。Because it is built on top of the ASP.NET MVC runtime, Web API automatically handles the low-level transport details of HTTP. 同时,Web API 自然公开 HTTP 编程模型。At the same time, Web API naturally exposes the HTTP programming model. 事实上,Web API 的一个目标是 会抽象出 HTTP 的现实。In fact, one goal of Web API is to not abstract away the reality of HTTP. 因此,Web API 既灵活又易于扩展。As a result, Web API is both flexible and easy to extend. 已证明 REST 体系结构样式是利用 HTTP 的有效方法,但它当然不是 HTTP 的唯一有效方法。The REST architectural style has proven to be an effective way to leverage HTTP - although it is certainly not the only valid approach to HTTP. 联系人管理器将公开 RESTful 以列出、添加和删除联系人,等等。The contact manager will expose the RESTful for listing, adding and removing contacts, among others.

此实验室需要基本了解 HTTP、REST,并假定你具有 HTML、JavaScript 和 jQuery 的基本工作知识。This lab requires a basic understanding of HTTP, REST, and assumes you have a basic working knowledge of HTML, JavaScript, and jQuery.

Note

ASP.NET 网站有一个专用于 ASP.NET Web API 框架的区域 https://asp.net/web-apiThe ASP.NET Web site has an area dedicated to the ASP.NET Web API framework at https://asp.net/web-api. 此站点将继续提供与 Web API 相关的最新信息、示例和新闻,因此,如果想要深入了解如何创建可用于几乎任何设备或开发框架的自定义 Web Api,请经常查看。This site will continue to provide late-breaking information, samples, and news related to Web API, so check it frequently if you'd like to delve deeper into the art of creating custom Web APIs available to virtually any device or development framework.

与 ASP.NET MVC 4 类似,ASP.NET Web API,在将服务层与控制器分离时具有很大的灵活性,使您可以很轻松地使用几个可用的依赖项注入框架。ASP.NET Web API, similar to ASP.NET MVC 4, has great flexibility in terms of separating the service layer from the controllers allowing you to use several of the available Dependency Injection frameworks fairly easy.

所有示例代码和代码段都包含在 Web 训练营培训工具包中,可从获取 https://go.microsoft.com/fwlink/?LinkID=248297&clcid=0x409All sample code and snippets are included in the Web Camps Training Kit, available at https://go.microsoft.com/fwlink/?LinkID=248297&clcid=0x409.

目标Objectives

在本动手实验中,您将了解如何:In this hands-on lab, you will learn how to:

  • 实现 RESTful Web APIImplement a RESTful Web API
  • 从 HTML 客户端调用 APICall the API from an HTML client

必备知识Prerequisites

完成本动手实验需要以下各项:The following is required to complete this hands-on lab:

设置Setup

安装代码片段Installing Code Snippets

为方便起见,你将通过此实验室管理的大部分代码都作为 Visual Studio code 片段提供。For convenience, much of the code you will be managing along this lab is available as Visual Studio code snippets. 若要安装代码段,请运行 .\Source\Setup\CodeSnippets.vsi 文件。To install the code snippets run .\Source\Setup\CodeSnippets.vsi file.

如果你不熟悉 Visual Studio Code 代码段,并且想要了解如何使用它们,则可以参考本文档中的附录 " A:使用代码片段 " 。If you are not familiar with the Visual Studio Code Snippets, and want to learn how to use them, you can refer to the appendix from this document "Appendix A: Using Code Snippets".

练习Exercises

此动手实验包括以下练习:This hands-on lab includes the following exercise:

  1. 练习1:创建 Read-Only Web APIExercise 1: Create a Read-Only Web API
  2. 练习2:创建读/写 Web APIExercise 2: Create a Read/Write Web API
  3. 练习3:使用 HTML 客户端中的 Web APIExercise 3: Consume the Web API from an HTML Client

Note

每个练习都带有一个 结束 文件夹,其中包含在完成练习后应获得的结果解决方案。Each exercise is accompanied by an End folder containing the resulting solution you should obtain after completing the exercises. 如果需要更多帮助,请使用此解决方案作为指导。You can use this solution as a guide if you need additional help working through the exercises.

完成本实验的估计时间: 60 分钟Estimated time to complete this lab: 60 minutes.

练习1:创建 Read-Only Web APIExercise 1: Create a Read-Only Web API

在此练习中,您将实现联系人管理器的只读 GET 方法。In this exercise, you will implement the read-only GET methods for the contact manager.

任务 1-创建 API 项目Task 1 - Creating the API Project

在此任务中,你将使用新的 ASP.NET web 项目模板创建 Web API web 应用程序。In this task, you will use the new ASP.NET web project templates to create a Web API web application.

  1. 运行 Visual Studio 2012 Express For Web,若要执行此操作,请单击 " 开始 ",然后键入 VS Express for Web 然后按 enterRun Visual Studio 2012 Express for Web, to do this go to Start and type VS Express for Web then press Enter.

  2. 从 " 文件 " 菜单中选择 " 新建项目"。From the File menu, select New Project. 选择 Visual c # | "项目类型" 树视图中的 "web 项目类型",然后选择 " ASP.NET MVC 4 Web 应用程序 " 项目类型。Select the Visual C# | Web project type from the project type tree view, then select the ASP.NET MVC 4 Web Application project type. 将项目的 名称 设置为 ContactManager ,将 解决方案名称 设置为 " 开始",然后单击 "确定"Set the project's Name to ContactManager and the Solution name to Begin, then click OK.

    创建新的 ASP.NET MVC 4.0 Web 应用程序项目Creating a new ASP.NET MVC 4.0 Web Application Project

    创建新的 ASP.NET MVC 4.0 Web 应用程序项目Creating a new ASP.NET MVC 4.0 Web Application Project

  3. 在 "ASP.NET MVC 4 项目类型" 对话框中,选择 " WEB API " 项目类型。In the ASP.NET MVC 4 project type dialog, select the Web API project type. 单击“确定”。Click OK.

    指定 Web API 项目类型Specifying the Web API project type

    指定 Web API 项目类型Specifying the Web API project type

任务 2-创建联系人管理器 API 控制器Task 2 - Creating the Contact Manager API Controllers

在此任务中,将创建 API 方法将驻留的控制器类。In this task, you will create the controller classes in which API methods will reside.

  1. 从项目中删除 "控制器" 文件夹中名为 " ValuesController.cs " 的文件。Delete the file named ValuesController.cs within Controllers folder from the project.

  2. 右键单击项目中的 " 控制器 " 文件夹,然后选择 " 添加 | 上下文菜单中的 "控制器"。Right-click the Controllers folder in the project and select Add | Controller from the context menu.

    向项目添加新控制器Adding a new controller to the project

    向项目添加新控制器Adding a new controller to the project

  3. 在出现的 " 添加控制器 " 对话框中,从 "模板" 菜单中选择 " 空 API 控制器 "。In the Add Controller dialog that appears, select Empty API Controller from the Template menu. 将 controller 类命名为 ContactControllerName the controller class ContactController. 然后单击 " 添加"。Then, click Add.

    ![使用 "添加控制器" 对话框创建新的 Web API 控制器](build-restful-apis-with-aspnet-web-api/_static/image4.png "使用 "添加控制器" 对话框创建新的 Web API 控制器")Using the Add Controller dialog to create a new Web API controller

    使用 "添加控制器" 对话框创建新的 Web API 控制器Using the Add Controller dialog to create a new Web API controller

  4. 将以下代码添加到 ContactController 中。Add the following code to the ContactController.

    (代码片段- WEB API Ex01-获取 API 方法) (Code Snippet - Web API Lab - Ex01 - Get API Method)

    public string[] Get()
    {
        return new string[]
        {
            "Hello",
            "World"
        };
    }
    
  5. F5 调试应用程序。Press F5 to debug the application. Web API 项目的默认主页应该会出现。The default home page for a Web API project should appear.

    ASP.NET Web API 应用程序的默认主页The default home page of an ASP.NET Web API application

    ASP.NET Web API 应用程序的默认主页The default home page of an ASP.NET Web API application

  6. 在 Internet Explorer 窗口中,按 F12 键打开 " 开发人员工具 " 窗口。In the Internet Explorer window, press the F12 key to open the Developer Tools window. 单击 " 网络 " 选项卡,然后单击 " 开始捕获 " 按钮,开始将网络流量捕获到该窗口中。Click the Network tab, and then click the Start Capturing button to begin capturing network traffic into the window.

    ![打开 "网络" 选项卡并启动网络捕获](build-restful-apis-with-aspnet-web-api/_static/image6.png "打开 "网络" 选项卡并启动网络捕获")Opening the network tab and initiating network capture

    打开 "网络" 选项卡并启动网络捕获Opening the network tab and initiating network capture

  7. 在浏览器的地址栏中追加 /api/contact ,并按 enter。Append the URL in the browser's address bar with /api/contact and press enter. 传输详细信息将出现在 "网络捕获" 窗口中。The transmission details will appear in the network capture window. 请注意,响应的 MIME 类型为 application/jsonNote that the response's MIME type is application/json. 这说明了默认输出格式为 JSON。This demonstrates how the default output format is JSON.

    ![在 "网络" 视图中查看 Web API 请求的输出](build-restful-apis-with-aspnet-web-api/_static/image7.png "在 "网络" 视图中查看 Web API 请求的输出")Viewing the output of the Web API request in the Network view

    在 "网络" 视图中查看 Web API 请求的输出Viewing the output of the Web API request in the Network view

    Note

    此时,Internet Explorer 10 的默认行为将询问用户是否想要保存或打开由 Web API 调用导致的流。Internet Explorer 10's default behavior at this point will be to ask if the user would like to save or open the stream resulting from the Web API call. 输出将是一个文本文件,其中包含 Web API URL 调用的 JSON 结果。The output will be a text file containing the JSON result of the Web API URL call. 不要取消对话框以便能够通过 "开发人员工具" 窗口监视响应的内容。Do not cancel the dialog in order to be able to watch the response's content through Developers Tool window.

  8. 单击 " 中转到详细视图 " 按钮,查看有关此 API 调用响应的详细信息。Click the Go to detailed view button to see more details about the response of this API call.

    切换到详细视图Switch to Detailed View

    切换到详细视图Switch to Detailed View

  9. 单击 " 响应正文 " 选项卡以查看实际的 JSON 响应文本。Click the Response body tab to view the actual JSON response text.

    查看网络监视器中的 JSON 输出文本Viewing the JSON output text in the network monitor

    查看网络监视器中的 JSON 输出文本Viewing the JSON output text in the network monitor

任务 3-创建联系人模型并增强联系人控制器Task 3 - Creating the Contact Models and Augment the Contact Controller

在此任务中,将创建 API 方法将驻留的控制器类。In this task, you will create the controller classes in which API methods will reside.

  1. 右键单击 " 模型 " 文件夹,然后选择 " 添加 |类 ... 从上下文菜单中。Right-click the Models folder and select Add | Class... from the context menu.

    向 web 应用程序添加新模型Adding a new model to the web application

    向 web 应用程序添加新模型Adding a new model to the web application

  2. 在 " 添加新项 " 对话框中,将新文件命名为 Contact.cs ,然后单击 " 添加"。In the Add New Item dialog, name the new file Contact.cs and click Add.

    创建新的 Contact 类文件Creating the new Contact class file

    创建新的 Contact 类文件Creating the new Contact class file

  3. 将以下突出显示的代码添加到 Contact 类。Add the following highlighted code to the Contact class.

    (代码片段- WEB API Ex01-Contact 类) (Code Snippet - Web API Lab - Ex01 - Contact Class)

    public class Contact
    {
        public int Id { get; set; }
    
        public string Name { get; set; }
    }
    
  4. ContactController 类中,选择 Get 方法的 "方法定义" 中的单词 字符串,然后键入 "联系人"。In the ContactController class, select the word string in method definition of the Get method, and type the word Contact. 键入单词后,就会在 word 联系人 的开头显示一个指示器。Once the word is typed in, an indicator will appear at the beginning of the word Contact. 按下 Ctrl 键并按句点 (。 ) 键,或使用鼠标单击图标以打开代码编辑器中的 "协助" 对话框,以自动填充 "模型" 命名空间的 using 指令。Either hold down the Ctrl key and press the period (.) key or click the icon using your mouse to open up the assistance dialog in the code editor, to automatically fill in the using directive for the Models namespace.

    使用 Intellisense 帮助命名空间声明

    使用 Intellisense 帮助命名空间声明Using Intellisense assistance for namespace declarations

  5. 修改 Get 方法的代码,使其返回联系人模型实例的数组。Modify the code for the Get method so that it returns an array of Contact model instances.

    (代码片段- WEB API Ex01-返回联系人列表) (Code Snippet - Web API Lab - Ex01 - Returning a list of contacts)

    public Contact[] Get()
    {
        return new Contact[]
        {
            new Contact
            {
                Id = 1,
                Name = "Glenn Block"
            },
            new Contact
            {
                Id = 2,
                Name = "Dan Roth"
            }
        };
    }
    
  6. F5 在浏览器中调试 web 应用程序。Press F5 to debug the web application in the browser. 若要查看对 API 的响应输出所做的更改,请执行以下步骤。To view the changes made to the response output of the API, perform the following steps.

    1. 打开浏览器后,如果开发人员工具尚未打开,请按 F12Once the browser opens, press F12 if the developer tools are not open yet.

    2. 单击 " 网络 " 选项卡。Click the Network tab.

    3. 按 " 开始捕获 " 按钮。Press the Start Capturing button.

    4. 将 URL 后缀 /api/contact 添加到地址栏中的 url,然后按 enter 键。Add the URL suffix /api/contact to the URL in the address bar and press the Enter key.

    5. 按 " 中转到详细视图 " 按钮。Press the Go to detailed view button.

    6. 选择 " 响应正文 " 选项卡。应该会看到一个 JSON 字符串,表示联系人实例的序列化形式。Select the Response body tab. You should see a JSON string representing the serialized form of an array of Contact instances.

      复杂的 Web API 方法调用的 JSON 序列化输出JSON serialized output of a complex Web API method call

      复杂的 Web API 方法调用的 JSON 序列化输出JSON serialized output of a complex Web API method call

任务 4-将功能提取到服务层Task 4 - Extracting Functionality into a Service Layer

此任务将演示如何将功能提取到服务层,使开发人员可以轻松地将其服务功能与控制器层分开,从而实现实际执行工作的服务的可重用性。This task will demonstrate how to extract functionality into a Service layer to make it easy for developers to separate their service functionality from the controller layer, thereby allowing reusability of the services that actually do the work.

  1. 在解决方案根文件夹中创建一个新文件夹并将其命名为 "it 服务"。Create a new folder in the solution root and name it Services. 为此,请右键单击 " ContactManager 项目",选择 "添加 | " "新建文件夹",将其命名为 "服务"。To do this, right-click ContactManager project, select Add | New Folder, name it Services.

    正在创建服务文件夹Creating Services folder

    正在创建服务文件夹Creating Services folder

  2. 右键单击 " 服务 " 文件夹,然后选择 " 添加 |类 ... 从上下文菜单中。Right-click the Services folder and select Add | Class... from the context menu.

    将新类添加到服务文件夹Adding a new class to the Services folder

    将新类添加到服务文件夹Adding a new class to the Services folder

  3. 当 " 添加新项 " 对话框出现时,将新类命名为 contacts.json ,然后单击 " 添加"。When the Add New Item dialog appears, name the new class ContactRepository and click Add.

    创建类文件以包含联系人存储库服务层的代码Creating a class file to contain the code for the Contact Repository service layer

    创建类文件以包含联系人存储库服务层的代码Creating a class file to contain the code for the Contact Repository service layer

  4. ContactRepository.cs 文件添加 using 指令以包括模型命名空间。Add a using directive to the ContactRepository.cs file to include the models namespace.

    using ContactManager.Models;
    
  5. 将以下突出显示的代码添加到 ContactRepository.cs 文件,以实现 GetAllContacts 方法。Add the following highlighted code to the ContactRepository.cs file to implement GetAllContacts method.

    (代码片段- WEB API Ex01-联系库) (Code Snippet - Web API Lab - Ex01 - Contact Repository)

    public class ContactRepository
    {
        public Contact[] GetAllContacts()
        {
            return new Contact[]
            {
                new Contact
                {
                    Id = 1,
                    Name = "Glenn Block"
                },
                new Contact
                {
                    Id = 2,
                    Name = "Dan Roth"
                }
            };
        }
    }
    
  6. 打开 ContactController.cs 文件(如果尚未打开)。Open the ContactController.cs file if it is not already open.

  7. 将以下 using 语句添加到文件的命名空间声明部分。Add the following using statement to the namespace declaration section of the file.

    using ContactManager.Services;
    
  8. 将以下突出显示的代码添加到 ContactController.cs 类,以添加一个私有字段以表示存储库的实例,以便其他类成员可以使用服务实现。Add the following highlighted code to the ContactController.cs class to add a private field to represent the instance of the repository, so that the rest of the class members can make use of the service implementation.

    (代码片段- WEB API Ex01-联系控制器) (Code Snippet - Web API Lab - Ex01 - Contact Controller)

    public class ContactController : ApiController
    {
        private ContactRepository contactRepository;
    
        public ContactController()
        {
            this.contactRepository = new ContactRepository();
        } 
        ...
    }
    
  9. 更改 Get 方法,使其能够使用联系人存储库服务。Change the Get method so that it makes use of the contact repository service.

    (代码片段- WEB API Ex01-通过存储库返回联系人列表) (Code Snippet - Web API Lab - Ex01 - Returning a list of contacts via the repository)

    public Contact[] Get()
    {
        return contactRepository.GetAllContacts();
    }
    
  10. ContactControllerGet 方法定义中放置一个断点。Put a breakpoint on the ContactController's Get method definition.

向联系人控制器添加断点Adding breakpoints to the contact controller

向联系人控制器添加断点Adding breakpoints to the contact controller 11. F5 运行该应用程序。Press F5 to run the application. 12. 当浏览器打开时,按 F12 打开开发人员工具。When the browser opens, press F12 to open the developer tools. 13. 单击 " 网络 " 选项卡。Click the Network tab. 14. 单击 " 开始捕获 " 按钮。Click the Start Capturing button. 15. 在地址栏中附加带有后缀 /api/contact 的 URL,然后按 enter 加载 api 控制器。Append the URL in the address bar with the suffix /api/contact and press Enter to load the API controller. 16. Get 方法开始执行时,Visual Studio 2012 应中断。Visual Studio 2012 should break once Get method begins execution.

在 Get 方法内中断Breaking within the Get method

在 Get 方法内中断Breaking within the Get method 17. 按 F5 以继续操作。Press F5 to continue. 18. 返回到 Internet Explorer (如果它尚未处于焦点上)。Go back to Internet Explorer if it is not already in focus. 请注意 "网络捕获" 窗口。Note the network capture window.

<span data-ttu-id="1d5c0-253">![Internet Explorer 中显示 Web API 调用结果的网络视图](build-restful-apis-with-aspnet-web-api/_static/image19.png "Internet Explorer 中显示 Web API 调用结果的网络视图")</span><span class="sxs-lookup"><span data-stu-id="1d5c0-253">![Network view in Internet Explorer showing results of the Web API call](build-restful-apis-with-aspnet-web-api/_static/image19.png "Network view in Internet Explorer showing results of the Web API call")</span></span>

<span data-ttu-id="1d5c0-254">*Internet Explorer 中显示 Web API 调用结果的网络视图*</span><span class="sxs-lookup"><span data-stu-id="1d5c0-254">*Network view in Internet Explorer showing results of the Web API call*</span></span>
  1. 单击 " 中转到详细视图 " 按钮。Click the Go to detailed view button.

  2. 单击 " 响应正文 " 选项卡。请注意 API 调用的 JSON 输出,以及它如何表示服务层检索到的两个联系人。Click the Response body tab. Note the JSON output of the API call, and how it represents the two contacts retrieved by the service layer.

    ![在 "开发人员工具" 窗口中查看 Web API 的 JSON 输出](build-restful-apis-with-aspnet-web-api/_static/image20.png "在 "开发人员工具" 窗口中查看 Web API 的 JSON 输出")Viewing the JSON output from the Web API in the developer tools window

    在 "开发人员工具" 窗口中查看 Web API 的 JSON 输出Viewing the JSON output from the Web API in the developer tools window

练习2:创建读/写 Web APIExercise 2: Create a Read/Write Web API

在此练习中,您将为联系人管理器实现 POST 和 PUT 方法,使其能够使用数据编辑功能。In this exercise, you will implement POST and PUT methods for the contact manager to enable it with data-editing features.

任务 1-打开 Web API 项目Task 1 - Opening the Web API Project

在此任务中,你将准备好改进在练习1中创建的 Web API 项目,以便它可以接受用户输入。In this task, you will prepare to enhance the Web API project created in Exercise 1 so that it can accept user input.

  1. 运行 Visual Studio 2012 Express For Web,若要执行此操作,请单击 " 开始 ",然后键入 VS Express for Web 然后按 enterRun Visual Studio 2012 Express for Web, to do this go to Start and type VS Express for Web then press Enter.

  2. 打开位于 Source/Ex02-ReadWriteWebAPI/begin/ Folder 的 begin 解决方案。Open the Begin solution located at Source/Ex02-ReadWriteWebAPI/Begin/ folder. 否则,你可以继续使用通过完成前一练习所获得的 最终 解决方案。Otherwise, you might continue using the End solution obtained by completing the previous exercise.

    1. 如果你打开了提供的 开始 解决方案,则需要下载一些缺少的 NuGet 包,然后再继续。If you opened the provided Begin solution, you will need to download some missing NuGet packages before continue. 为此,请单击 " 项目 " 菜单并选择 " 管理 NuGet 包"。To do this, click the Project menu and select Manage NuGet Packages.

    2. 在 " 管理 NuGet 包 " 对话框中,单击 " 还原 " 以下载缺少的包。In the Manage NuGet Packages dialog, click Restore in order to download missing packages.

    3. 最后,通过单击 "生成" "生成解决方案" 来生成解决方案 | 。Finally, build the solution by clicking Build | Build Solution.

      Note

      使用 NuGet 的优点之一是,无需将所有库都送到项目中,从而减少了项目的大小。One of the advantages of using NuGet is that you don't have to ship all the libraries in your project, reducing the project size. 使用 NuGet 功能,通过指定 Packages.config 文件中的包版本,你将能够在首次运行项目时下载所有必需的库。With NuGet Power Tools, by specifying the package versions in the Packages.config file, you will be able to download all the required libraries the first time you run the project. 这就是在从此实验室打开现有解决方案之后需要运行这些步骤的原因。This is why you will have to run these steps after you open an existing solution from this lab.

  3. 打开 Services/contacts.json 文件。Open the Services/ContactRepository.cs file.

任务 2-将 Data-Persistence 功能添加到联系人存储库实现Task 2 - Adding Data-Persistence Features to the Contact Repository Implementation

在此任务中,您将补充在练习1中创建的 Web API 项目的 Contacts.json 类,使其可以持久保存并接受用户输入和新的联系人实例。In this task, you will augment the ContactRepository class of the Web API project created in Exercise 1 so that it can persist and accept user input and new Contact instances.

  1. 将以下常量添加到 contacts.json 类中,以表示在本练习后面的 web 服务器缓存项密钥名称。Add the following constant to the ContactRepository class to represent the name of the web server cache item key name later in this exercise.

    private const string CacheKey = "ContactStore";
    
  2. 将构造函数添加到包含以下代码的 contacts.jsonAdd a constructor to the ContactRepository containing the following code.

    (代码片段- Ex02 联系存储库构造函数) (Code Snippet - Web API Lab - Ex02 - Contact Repository Constructor)

    public ContactRepository()
    {
        var ctx = HttpContext.Current;
    
        if (ctx != null)
        {
            if (ctx.Cache[CacheKey] == null)
            {
                var contacts = new Contact[]
                {
                    new Contact
                    {
                        Id = 1, Name = "Glenn Block"
                    },
                    new Contact
                    {
                        Id = 2, Name = "Dan Roth"
                    }
                };
    
                ctx.Cache[CacheKey] = contacts;
            }
        }
    }
    
  3. 修改 GetAllContacts 方法的代码,如下所示。Modify the code for the GetAllContacts method as demonstrated below.

    (代码片段- WEB API Ex02-获取所有联系人) (Code Snippet - Web API Lab - Ex02 - Get All Contacts)

    public Contact[] GetAllContacts()
    {
        var ctx = HttpContext.Current;
    
        if (ctx != null)
        {
            return (Contact[])ctx.Cache[CacheKey];
        }
    
        return new Contact[]
            {
                new Contact
                {
                    Id = 0,
                    Name = "Placeholder"
                }
            };
    }
    

    Note

    此示例用于演示目的,并将 web 服务器的缓存用作存储介质,使多个客户端的值可以同时用于多个客户端,而不是使用会话存储机制或请求存储生存期。This example is for demonstration purposes and will use the web server's cache as a storage medium, so that the values will be available to multiple clients simultaneously, rather than use a Session storage mechanism or a Request storage lifetime. 可以使用实体框架、XML 存储或任何其他种类的 web 服务器缓存。One could use Entity Framework, XML storage, or any other variety in place of the web server cache.

  4. contacts.json 类实现一个名为 SaveContact 的新方法,以便保存联系人。Implement a new method named SaveContact to the ContactRepository class to do the work of saving a contact. SaveContact 方法应采用单个 Contact 参数,并返回指示成功或失败的布尔值。The SaveContact method should take a single Contact parameter and return a Boolean value indicating success or failure.

    (代码片段- WEB API Ex02-实现 SaveContact 方法) (Code Snippet - Web API Lab - Ex02 - Implementing the SaveContact Method)

    public bool SaveContact(Contact contact)
    {
        var ctx = HttpContext.Current;
    
        if (ctx != null)
        {
             try
             {
                  var currentData = ((Contact[])ctx.Cache[CacheKey]).ToList();
                  currentData.Add(contact);
                  ctx.Cache[CacheKey] = currentData.ToArray();
    
                  return true;
             }
             catch (Exception ex)
             {
                  Console.WriteLine(ex.ToString());
                  return false;
             }
        }
    
        return false;
    }
    

练习3:使用 HTML 客户端中的 Web APIExercise 3: Consume the Web API from an HTML Client

在此练习中,您将创建一个 HTML 客户端来调用 Web API。In this exercise, you will create an HTML client to call the Web API. 此客户端将使用 JavaScript 简化与 Web API 的数据交换,并使用 HTML 标记在 web 浏览器中显示结果。This client will facilitate data exchange with the Web API using JavaScript and will display the results in a web browser using HTML markup.

任务 1-修改索引视图以提供用于显示联系人的 GUITask 1 - Modifying the Index View to Provide a GUI for Displaying Contacts

在此任务中,您将修改 web 应用程序的默认索引视图,以支持在 HTML 浏览器中显示现有联系人列表的要求。In this task, you will modify the default Index view of the web application to support the requirement of displaying the list of existing contacts in an HTML browser.

  1. 如果尚未打开,请打开 Visual Studio 2012 Express For WebOpen Visual Studio 2012 Express for Web if it is not already open.

  2. 打开位于 Source/Ex03-ConsumingWebAPI/begin/ Folder 的 begin 解决方案。Open the Begin solution located at Source/Ex03-ConsumingWebAPI/Begin/ folder. 否则,你可以继续使用通过完成前一练习所获得的 最终 解决方案。Otherwise, you might continue using the End solution obtained by completing the previous exercise.

    1. 如果你打开了提供的 开始 解决方案,则需要下载一些缺少的 NuGet 包,然后再继续。If you opened the provided Begin solution, you will need to download some missing NuGet packages before continue. 为此,请单击 " 项目 " 菜单并选择 " 管理 NuGet 包"。To do this, click the Project menu and select Manage NuGet Packages.

    2. 在 " 管理 NuGet 包 " 对话框中,单击 " 还原 " 以下载缺少的包。In the Manage NuGet Packages dialog, click Restore in order to download missing packages.

    3. 最后,通过单击 "生成" "生成解决方案" 来生成解决方案 | 。Finally, build the solution by clicking Build | Build Solution.

      Note

      使用 NuGet 的优点之一是,无需将所有库都送到项目中,从而减少了项目的大小。One of the advantages of using NuGet is that you don't have to ship all the libraries in your project, reducing the project size. 使用 NuGet 功能,通过指定 Packages.config 文件中的包版本,你将能够在首次运行项目时下载所有必需的库。With NuGet Power Tools, by specifying the package versions in the Packages.config file, you will be able to download all the required libraries the first time you run the project. 这就是在从此实验室打开现有解决方案之后需要运行这些步骤的原因。This is why you will have to run these steps after you open an existing solution from this lab.

  3. 打开位于 Views/Home 文件夹中的 索引 cshtml 文件。Open the Index.cshtml file located at Views/Home folder.

  4. 用 id 替换 div 元素中的 HTML 代码,使其类似于以下代码。Replace the HTML code within the div element with id body so that it looks like the following code.

    <div id="body">
        <ul id="contacts"></ul>
    </div>
    
  5. 在文件底部添加以下 Javascript 代码,以对 Web API 执行 HTTP 请求。Add the following Javascript code at the bottom of the file to perform the HTTP request to the Web API.

    @section scripts{
    <script type="text/javascript">
    $(function()
    {
            $.getJSON('/api/contact', function(contactsJsonPayload)
            {
                $(contactsJsonPayload).each(function(i, item)
                {
                    $('#contacts').append('<li>' + item.Name + '</li>');
                });
            });
    });
    </script>
    }
    
  6. 打开 ContactController.cs 文件(如果尚未打开)。Open the ContactController.cs file if it is not already open.

  7. ContactController 类的 Get 方法上放置一个断点。Place a breakpoint on the Get method of the ContactController class.

    在 API 控制器的 Get 方法上放置断点Placing a breakpoint on the Get method of the API controller

    在 API 控制器的 Get 方法上放置断点Placing a breakpoint on the Get method of the API controller

  8. F5 运行项目。Press F5 to run the project. 浏览器将加载 HTML 文档。The browser will load the HTML document.

    Note

    确保浏览到应用程序的根 URL。Ensure that you are browsing to the root URL of your application.

  9. 加载页面并执行 JavaScript 后,断点将被命中,代码执行将在控制器中暂停。Once the page loads and the JavaScript executes, the breakpoint will be hit and the code execution will pause in the controller.

    使用 VS Express for Web 调试到 Web API 调用Debugging into the Web API calls using VS Express for Web

    使用 Visual Studio 2012 Express for Web 调试到 Web API 调用Debugging into the Web API call using Visual Studio 2012 Express for Web

  10. 删除断点,然后按 F5 或 "调试" 工具栏的 " 继续 " 按钮,继续在浏览器中加载视图。Remove the breakpoint and press F5 or the debugging toolbar's Continue button to continue loading the view in the browser. Web API 调用完成后,会在浏览器中看到从 Web API 调用返回的、显示为列表项的联系人。Once the Web API call completes you should see the contacts returned from the Web API call displayed as list items in the browser.

    在浏览器中显示为列表项的 API 调用结果Results of the API call displayed in the browser as list items

    在浏览器中显示为列表项的 API 调用结果Results of the API call displayed in the browser as list items

  11. 停止调试。Stop debugging.

任务 2-修改索引视图以提供用于创建联系人的 GUITask 2 - Modifying the Index View to Provide a GUI for Creating Contacts

在此任务中,您将继续修改 MVC 应用程序的索引视图。In this task, you will continue to modify the Index view of the MVC application. 将在 HTML 页中添加一个窗体,该页面将捕获用户输入并将其发送到 Web API 来创建新的联系人,并将创建新的 Web API 控制器方法以从 GUI 收集日期。A form will be added to the HTML page that will capture user input and send it to the Web API to create a new Contact, and a new Web API controller method will be created to collect date from the GUI.

  1. 打开 ContactController.cs 文件。Open the ContactController.cs file.

  2. 将新方法添加到名为 Post 的控制器类,如下面的代码所示。Add a new method to the controller class named Post as shown in the following code.

    (代码片段- WEB API Ex03-Post 方法) (Code Snippet - Web API Lab - Ex03 - Post Method)

    public HttpResponseMessage Post(Contact contact)
    {
        this.contactRepository.SaveContact(contact);
    
        var response = Request.CreateResponse<Contact>(System.Net.HttpStatusCode.Created, contact);
    
        return response;
    }
    
  3. 在 Visual Studio 中打开 索引 cshtml 文件(如果尚未打开)。Open the Index.cshtml file in Visual Studio if it is not already open.

  4. 将以下 HTML 代码添加到文件中,就在上一个任务中添加的未排序列表之后。Add the HTML code below to the file just after the unordered list you added in the previous task.

    <form id="saveContactForm" method="post">
    <h3>Create a new Contact</h3>
    <p>
        <label for="contactId">Contact Id:</label>
        <input type="text" name="Id" />
    </p>
    <p>
        <label for="contactName">Contact Name:</label>
        <input type="text" name="Name" />
    </p>
    <input type="button" id="saveContact" value="Save" />
    </form>
    
  5. 在文档底部的脚本元素中,添加以下突出显示的代码以处理按钮单击事件,这会使用 HTTP POST 调用将数据发布到 Web API。Within the script element at the bottom of the document, add the following highlighted code to handle button-click events, which will post the data to the Web API using an HTTP POST call.

    <script type="text/javascript">
    ... 
    $('#saveContact').click(function()
             {
                  $.post("api/contact",
                        $("#saveContactForm").serialize(),
                        function(value)
                        {
                             $('#contacts').append('<li>' + value.Name + '</li>');
                        },
                        "json"
                  );
             });
    </script>
    
  6. ContactController.cs 中,将一个断点置于 Post 方法上。In ContactController.cs, place a breakpoint on the Post method.

  7. F5 在浏览器中运行该应用程序。Press F5 to run the application in the browser.

  8. 在浏览器中加载页面后,键入新的联系人名称和 Id,并单击 " 保存 " 按钮。Once the page is loaded in the browser, type in a new contact name and Id and click the Save button.

    在浏览器中加载的客户端 HTML 文档The client HTML document loaded in the browser

    在浏览器中加载的客户端 HTML 文档The client HTML document loaded in the browser

  9. 调试器窗口在 Post 方法中中断时,查看 contact 参数的属性。When the debugger window breaks in the Post method, take a look at the properties of the contact parameter. 值应与您在窗体中输入的数据匹配。The values should match the data you entered in the form.

    要从客户端发送到 Web API 的联系人对象The Contact object being sent to the Web API from the client

    要从客户端发送到 Web API 的联系人对象The Contact object being sent to the Web API from the client

  10. 在调试器中单步执行方法,直到创建了 响应 变量为止。Step through the method in the debugger until the response variable has been created. 在调试器的 " 局部变量 " 窗口中进行检查后,您将看到已设置所有属性。Upon inspection in the Locals window in the debugger, you'll see that all the properties have been set.

在调试器中创建后的响应The response following creation in the debugger

在调试器中创建后的响应The response following creation in the debugger 11. 如果按 F5 或单击调试器中的 " 继续 ",请求将会完成。If you press F5 or click Continue in the debugger the request will complete. 切换回浏览器后,会将新联系人添加到 contacts.json 实现存储的联系人列表中。Once you switch back to the browser, the new contact has been added to the list of contacts stored by the ContactRepository implementation.

浏览器反映新联系人实例的创建成功The browser reflects successful creation of the new contact instance

浏览器反映新联系人实例的创建成功The browser reflects successful creation of the new contact instance

Note

此外,你可以遵循 附录 C:使用 Web 部署发布 ASP.NET MVC 4 应用程序,将此应用程序部署到 Azure。Additionally, you can deploy this application to Azure following Appendix C: Publishing an ASP.NET MVC 4 Application using Web Deploy.


总结Summary

此实验室已向你介绍了新的 ASP.NET Web API 框架,以及如何使用框架实现 RESTful Web Api。This lab has introduced you to the new ASP.NET Web API framework and to the implementation of RESTful Web APIs using the framework. 从这里,你可以创建一个新的存储库,该存储库使用任意数量的机制和网络连接,而不是在此实验室中作为示例提供的简单数据。From here, you could create a new repository that facilitates data persistence using any number of mechanisms and wire that service up rather than the simple one provided as an example in this lab. Web API 支持多种附加功能,例如,从以支持 HTTP 和 JSON 或 XML 的任何语言编写的非 HTML 客户端进行通信。Web API supports a number of additional features, such as enabling communication from non-HTML clients written in any language that supports HTTP and JSON or XML. 还可以在典型的 web 应用程序之外承载 Web API,还可以创建自己的序列化格式。The ability to host a Web API outside of a typical web application is also possible, as well as is the ability to create your own serialization formats.

ASP.NET 网站有一个专用于 ASP.NET Web API 框架的区域 [https://asp.net/web-api](https://asp.net/web-api) 。The ASP.NET Web site has an area dedicated to the ASP.NET Web API framework at [https://asp.net/web-api](https://asp.net/web-api). 此站点将继续提供与 Web API 相关的最新信息、示例和新闻,因此,如果想要深入了解如何创建可用于几乎任何设备或开发框架的自定义 Web Api,请经常查看。This site will continue to provide late-breaking information, samples, and news related to Web API, so check it frequently if you'd like to delve deeper into the art of creating custom Web APIs available to virtually any device or development framework.

附录 A:使用代码片段Appendix A: Using Code Snippets

使用代码片段,您可以随时获得所需的全部代码。With code snippets, you have all the code you need at your fingertips. 实验室文档将告诉你何时可以使用它们,如下图所示。The lab document will tell you exactly when you can use them, as shown in the following figure.

使用 Visual Studio code 代码段将代码插入到项目中Using Visual Studio code snippets to insert code into your project

使用 Visual Studio code 代码段将代码插入到项目中Using Visual Studio code snippets to insert code into your project

使用键盘 (仅限 c # 添加代码片段) To add a code snippet using the keyboard (C# only)

  1. 将光标放在要插入代码的位置。Place the cursor where you would like to insert the code.

  2. 开始键入代码片段名称 (没有空格或连字符) 。Start typing the snippet name (without spaces or hyphens).

  3. 请注意,IntelliSense 显示匹配的代码段名称。Watch as IntelliSense displays matching snippets' names.

  4. 选择正确的代码段 (或保留键入内容,直到选择了整个代码段的名称) 。Select the correct snippet (or keep typing until the entire snippet's name is selected).

  5. 按 Tab 键两次,将代码段插入到光标位置。Press the Tab key twice to insert the snippet at the cursor location.

    开始键入代码片段名称Start typing the snippet name

    开始键入代码片段名称Start typing the snippet name

    按 Tab 键以选择突出显示的代码段Press Tab to select the highlighted snippet

    按 Tab 键以选择突出显示的代码段Press Tab to select the highlighted snippet

    再次按 Tab 键,代码片段将展开Press Tab again and the snippet will expand

    再次按 Tab 键,代码片段将展开Press Tab again and the snippet will expand

若要使用鼠标 (c # 中添加代码段,请 Visual Basic 和 XML) To add a code snippet using the mouse (C#, Visual Basic and XML)

  1. 右键单击要插入代码片段的位置。Right-click where you want to insert the code snippet.

  2. 选择 " 插入 代码片段",然后选择 "我的代码片段"Select Insert Snippet followed by My Code Snippets.

  3. 通过单击从列表中选择相关的代码片段。Pick the relevant snippet from the list, by clicking on it.

    ![右键单击要插入代码片段的位置,然后选择 "插入代码片段"](build-restful-apis-with-aspnet-web-api/_static/image32.png "右键单击要插入代码片段的位置,然后选择 "插入代码片段"")Right-click where you want to insert the code snippet and select Insert Snippet

    右键单击要插入代码片段的位置,然后选择 "插入代码片段"Right-click where you want to insert the code snippet and select Insert Snippet

    通过单击从列表中选择相关的代码片段Pick the relevant snippet from the list, by clicking on it

    通过单击从列表中选择相关的代码片段Pick the relevant snippet from the list, by clicking on it

附录 B:安装 Web Visual Studio Express 2012Appendix B: Installing Visual Studio Express 2012 for Web

你可以使用 Microsoft Web 平台安装程序安装 Web Microsoft Visual Studio Express 2012 或其他 " Express " 版本。 You can install Microsoft Visual Studio Express 2012 for Web or another "Express" version using the Microsoft Web Platform Installer. 以下说明将指导你完成使用 Microsoft Web 平台安装程序 安装 Visual studio Express 2012 for Web 的步骤。The following instructions guide you through the steps required to install Visual studio Express 2012 for Web using Microsoft Web Platform Installer.

  1. 请参阅 [https://go.microsoft.com/?linkid=9810169](https://go.microsoft.com/?linkid=9810169) 。Go to [https://go.microsoft.com/?linkid=9810169](https://go.microsoft.com/?linkid=9810169). 或者,如果你已经安装了 Web 平台安装程序,则可以打开它,并 " 使用 Azure SDK 搜索产品 Visual Studio Express 2012 for Web " 。Alternatively, if you already have installed Web Platform Installer, you can open it and search for the product "Visual Studio Express 2012 for Web with Azure SDK".

  2. 单击 " 立即安装"。Click on Install Now. 如果你没有 Web 平台安装程序 ,则会重定向到 "下载并安装"。If you do not have Web Platform Installer you will be redirected to download and install it first.

  3. Web 平台安装程序 打开后,单击 "安装" 以启动安装程序。Once Web Platform Installer is open, click Install to start the setup.

    安装 Visual Studio ExpressInstall Visual Studio Express

    安装 Visual Studio ExpressInstall Visual Studio Express

  4. 阅读所有产品的许可证和条款,单击 " 我接受 " 以继续。Read all the products' licenses and terms and click I Accept to continue.

    接受许可条款

    接受许可条款Accepting the license terms

  5. 等待下载和安装过程完成。Wait until the downloading and installation process completes.

    安装进度

    安装进度Installation progress

  6. 安装完成后,单击 " 完成"。When the installation completes, click Finish.

    安装完成

    安装完成Installation completed

  7. 单击 " 退出 " 以关闭 Web 平台安装程序。Click Exit to close Web Platform Installer.

  8. 若要打开 Web Visual Studio Express,请在 "开始" 屏幕上,单击 "开始撰写 " VS Express " ",然后单击 " VS Express for Web " 磁贴。To open Visual Studio Express for Web, go to the Start screen and start writing "VS Express", then click on the VS Express for Web tile.

    VS Express for Web 磁贴

    VS Express for Web 磁贴VS Express for Web tile

附录 C:使用 Web 部署发布 ASP.NET MVC 4 应用程序Appendix C: Publishing an ASP.NET MVC 4 Application using Web Deploy

本附录将演示如何从 Azure 门户创建新网站,以及如何利用 Azure 提供的 Web 部署发布功能,发布通过实验室获取的应用程序。This appendix will show you how to create a new web site from the Azure Portal and publish the application you obtained by following the lab, taking advantage of the Web Deploy publishing feature provided by Azure.

任务 1-从 Azure 门户创建新网站Task 1 - Creating a New Web Site from the Azure Portal

  1. 请使用 Azure 管理门户 ,并使用与你的订阅关联的 Microsoft 凭据登录。Go to the Azure Management Portal and sign in using the Microsoft credentials associated with your subscription.

    Note

    借助 Azure,你可以免费托管10个 ASP.NET 的网站,然后随着流量的增长进行扩展。With Azure you can host 10 ASP.NET Web Sites for free and then scale as your traffic grows. 你可以在 此处注册。You can sign up here.

    登录到 Microsoft Azure 门户Log on to Windows Azure portal

    登录到门户Log on to Portal

  2. 单击命令栏上的 " 新建 "。Click New on the command bar.

    创建新网站Creating a new Web Site

    创建新网站Creating a new Web Site

  3. 单击 "计算 | 网站"Click Compute | Web Site. 然后选择 " 快速创建 " 选项。Then select Quick Create option. 为新网站提供可用 URL,并单击 " 创建 网站"。Provide an available URL for the new web site and click Create Web Site.

    Note

    Azure 是在云中运行的 web 应用程序的宿主,你可以控制和管理这些应用程序。Azure is the host for a web application running in the cloud that you can control and manage. 使用 "快速创建" 选项,可以从门户外部将已完成的 web 应用程序部署到 Azure。The Quick Create option allows you to deploy a completed web application to the Azure from outside the portal. 它不包括设置数据库的步骤。It does not include steps for setting up a database.

    使用“快速创建”创建新网站Creating a new Web Site using Quick Create

    使用“快速创建”创建新网站Creating a new Web Site using Quick Create

  4. 等到新网站创建完毕。Wait until the new Web Site is created.

  5. 创建网站后,单击 " URL " 列下的链接。Once the Web Site is created click the link under the URL column. 检查新网站是否正常工作。Check that the new Web Site is working.

    浏览到新网站Browsing to the new web site

    浏览到新网站Browsing to the new web site

    网站正在运行Web site running

    网站正在运行Web site running

  6. 返回到门户,并在 " 名称 " 列下单击网站的名称以显示管理页面。Go back to the portal and click the name of the web site under the Name column to display the management pages.

    打开网站管理页Opening the web site management pages

    打开网站管理页Opening the Web Site management pages

  7. 在 " 仪表板 " 页的 " 速览 " 部分下,单击 " 下载发布配置文件 " 链接。In the Dashboard page, under the quick glance section, click the Download publish profile link.

    Note

    发布配置文件 包含为每个已启用的发布方法将 web 应用程序发布到 Azure 所需的所有信息。The publish profile contains all of the information required to publish a web application to a Azure for each enabled publication method. 发布配置文件包含有连接到并且验证该发布方法启用的每个端点所需的 URL、用户凭据和数据库字符串。The publish profile contains the URLs, user credentials and database strings required to connect to and authenticate against each of the endpoints for which a publication method is enabled. Microsoft WebMatrix 2Microsoft Visual Studio Express for WebMicrosoft Visual Studio 2012 支持读取发布配置文件,以便自动配置这些程序以将 Web 应用程序发布到 Azure。Microsoft WebMatrix 2, Microsoft Visual Studio Express for Web and Microsoft Visual Studio 2012 support reading publish profiles to automate configuration of these programs for publishing web applications to Azure.

    下载网站发布配置文件Downloading the web site publish profile

    下载网站发布配置文件Downloading the Web Site publish profile

  8. 将发布配置文件下载到已知位置。Download the publish profile file to a known location. 在本练习中,你将了解如何使用此文件从 Visual Studio 将 web 应用程序发布到 Azure。Further in this exercise you will see how to use this file to publish a web application to Azure from Visual Studio.

    正在保存发布配置文件Saving the publish profile file

    正在保存发布配置文件Saving the publish profile file

任务 2-配置数据库服务器Task 2 - Configuring the Database Server

如果应用程序使用 SQL Server 数据库,则需要创建 SQL 数据库服务器。If your application makes use of SQL Server databases you will need to create a SQL Database server. 如果要部署不使用 SQL Server 的简单应用程序,则可以跳过此任务。If you want to deploy a simple application that does not use SQL Server you might skip this task.

  1. 你将需要一个用于存储应用程序数据库的 SQL 数据库服务器。You will need a SQL Database server for storing the application database. 可以在 Azure 管理门户中的 sql 数据库 | 服务器 | 的仪表板 上查看订阅中的 sql 数据库服务器。You can view the SQL Database servers from your subscription in the Azure Management portal at Sql Databases | Servers | Server's Dashboard. 如果尚未创建服务器,可以使用命令栏上的 " 添加 " 按钮创建一个服务器。If you do not have a server created, you can create one using the Add button on the command bar. 记下 服务器名称和 URL、管理员登录名和密码,因为你将在后续任务中使用它们。Take note of the server name and URL, administrator login name and password, as you will use them in the next tasks. 请不要创建数据库,因为它将在后面的阶段创建。Do not create the database yet, as it will be created in a later stage.

    SQL 数据库服务器仪表板SQL Database Server Dashboard

    SQL 数据库服务器仪表板SQL Database Server Dashboard

  2. 在下一任务中,您将从 Visual Studio 测试数据库连接,因此,需要在服务器的 允许 IP 地址 列表中包含本地 ip 地址。In the next task you will test the database connection from Visual Studio, for that reason you need to include your local IP address in the server's list of Allowed IP Addresses. 要执行此操作,请单击 " 配置",从 " 当前客户端 IP 地址 " 选择 ip 地址,并将其粘贴到 " 起始 Ip 地址 " 和 " 结束 ip 地址 " 文本框中,然后单击 "  添加-客户端-IP 地址-确定" 按钮。To do that, click Configure, select the IP address from Current Client IP Address and paste it on the Start IP Address and End IP Address text boxes and click the add-client-ip-address-ok-button button.

    添加客户端 IP 地址

    添加客户端 IP 地址Adding Client IP Address

  3. 客户端 Ip 地址 添加到 "允许的 IP 地址" 列表中后,单击 " 保存 " 以确认更改。Once the Client IP Address is added to the allowed IP addresses list, click on Save to confirm the changes.

    确认更改

    确认更改Confirm Changes

任务 3-使用 Web 部署发布 ASP.NET MVC 4 应用程序Task 3 - Publishing an ASP.NET MVC 4 Application using Web Deploy

  1. 返回到 ASP.NET MVC 4 解决方案。Go back to the ASP.NET MVC 4 solution. 解决方案资源管理器 中,右键单击网站项目,然后选择 " 发布"。In the Solution Explorer, right-click the web site project and select Publish.

    发布应用程序Publishing the Application

    发布网站Publishing the web site

  2. 导入您在第一个任务中保存的发布配置文件。Import the publish profile you saved in the first task.

    导入发布配置文件Importing the publish profile

    导入发布配置文件Importing publish profile

  3. 单击 " 验证连接"。Click Validate Connection. 验证完成后,单击 " 下一步"。Once Validation is complete click Next.

    Note

    验证完成后,"验证连接" 按钮旁边会出现一个绿色的复选标记。Validation is complete once you see a green checkmark appear next to the Validate Connection button.

    正在验证连接Validating connection

    正在验证连接Validating connection

  4. 在 " 设置 " 页的 " 数据库 " 部分下,单击数据库连接的文本框旁边的按钮, (DefaultConnection) 。In the Settings page, under the Databases section, click the button next to your database connection's textbox (i.e. DefaultConnection).

    Web 部署配置Web deploy configuration

    Web 部署配置Web deploy configuration

  5. 按如下所示配置数据库连接:Configure the database connection as follows:

    • 在 " 服务器名称 " 中,键入您的 SQL 数据库服务器 URL,使用 tcp: prefix。In the Server name type your SQL Database server URL using the tcp: prefix.

    • 在 " 用户名 " 中键入服务器管理员登录名。In User name type your server administrator login name.

    • 在 " 密码 " 中键入服务器管理员登录密码。In Password type your server administrator login password.

    • 键入新的数据库名称,例如: MVC4SampleDBType a new database name, for example: MVC4SampleDB.

      正在配置目标连接字符串Configuring destination connection string

      正在配置目标连接字符串Configuring destination connection string

  6. Then click OK. 系统提示创建数据库时,单击 "是"When prompted to create the database click Yes.

    创建数据库Creating the database

    创建数据库Creating the database

  7. 将用于连接到 Windows Azure 中的 SQL 数据库的连接字符串显示在 "默认连接" 文本框中。The connection string you will use to connect to SQL Database in Windows Azure is shown within Default Connection textbox. 然后单击“下一步”。Then click Next.

    指向 SQL 数据库的连接字符串Connection string pointing to SQL Database

    指向 SQL 数据库的连接字符串Connection string pointing to SQL Database

  8. 在 " 预览 " 页上,单击 " 发布"。In the Preview page, click Publish.

    发布 web 应用程序Publishing the web application

    发布 web 应用程序Publishing the web application

  9. 发布过程完成后,您的默认浏览器将打开已发布的网站。Once the publishing process finishes, your default browser will open the published web site.

    发布到 Windows Azure 的应用程序Application published to Windows Azure

    已将应用程序发布到 AzureApplication published to Azure