ASP.NET MVC 教程:使用 Azure Cosmos DB 进行 Web 应用程序开发ASP.NET MVC Tutorial: Web application development with Azure Cosmos DB

为了特别说明可以如何有效地利用 Azure Cosmos DB 来存储和查询 JSON 文档,本文提供了演示如何使用 Azure Cosmos DB 构建待办事项应用的完整演练。To highlight how you can efficiently leverage Azure Cosmos DB to store and query JSON documents, this article provides an end-to-end walk-through showing you how to build a todo app using Azure Cosmos DB. 任务存储为 Azure Cosmos DB 中的 JSON 文档。The tasks will be stored as JSON documents in Azure Cosmos DB.

屏幕截图:“ASP NET MVC 教程分步说明”教程创建的待办事项列表 MVC Web 应用程序

本演练演示如何使用 Azure Cosmos DB 服务从 Azure 上托管的 ASP.NET MVC Web 应用程序来存储和访问数据。This walk-through shows you how to use the Azure Cosmos DB service to store and access data from an ASP.NET MVC web application hosted on Azure. 如果正在寻找只侧重于 Azure Cosmos DB 而不是 ASP.NET MVC 组件的教程,请参阅 构建 Azure Cosmos DB C# 控制台应用程序If you're looking for a tutorial that focuses only on Azure Cosmos DB, and not the ASP.NET MVC components, see Build an Azure Cosmos DB C# console application.

Tip

本教程假设读者先前有使用 ASP.NET MVC 和 Azure 网站的经验。 如果不熟悉 ASP.NET 或必备工具,我们建议从 GitHub 下载完整的示例项目,并按照此示例中的说明操作。 构建之后,可以回顾本文以深入了解项目上下文中的代码。

本数据库教程的先决条件Prerequisites for this database tutorial

在按照本文中的说明操作之前,应确保已拥有下列项:Before following the instructions in this article, you should ensure that you have the following:

  • 有效的 Azure 帐户。An active Azure account. 如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

    可以使用 URI 为 https://localhost:8081Azure Cosmos DB 模拟器You can use the Azure Cosmos DB Emulator with a URI of https://localhost:8081. 对请求进行身份验证中提供了主密钥。The Primary Key is provided in Authenticating requests.

  • 如果尚未安装 Visual Studio 2017,可以下载并使用免费的 Visual Studio 2017 Community EditionIf you don't already have Visual Studio 2017 installed, you can download and use the free Visual Studio 2017 Community Edition. 在安装 Visual Studio 的过程中,请确保启用“Azure 开发”工作负荷。Make sure that you enable Azure development workload during the Visual Studio setup.

  • 针对 Visual Studio 2017 的用于 .NET 的 Azure SDK,可通过 Visual Studio 安装程序获得。Azure SDK for .NET for Visual Studio 2017, available through the Visual Studio Installer.

本文中的所有屏幕截图均使用 Microsoft Visual Studio Community 2017 采集。All the screenshots in this article have been taken using Microsoft Visual Studio Community 2017. 如果系统配备了不同的版本,那么,屏幕和选项可能不会完全相符,但只要符合上述先决条件,本解决方案应该还是有效。If your system is configured with a different version it is possible that your screens and options won't match entirely, but if you meet the above prerequisites this solution should work.

步骤 1:创建 Azure Cosmos DB 数据库帐户Step 1: Create an Azure Cosmos DB database account

首先创建一个 Azure Cosmos DB 帐户。Let's start by creating an Azure Cosmos DB account. 如果已有一个 Azure Cosmos DB SQL 帐户,或者要在本教程中使用 Azure Cosmos DB 模拟器,可以跳到创建新的 ASP.NET MVC 应用程序If you already have a SQL account for Azure Cosmos DB or if you are using the Azure Cosmos DB Emulator for this tutorial, you can skip to Create a new ASP.NET MVC application.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 选择“创建资源” > “数据库” > “Azure Cosmos DB”。Select Create a resource > Databases > Azure Cosmos DB.

    Azure 门户“数据库”窗格

  3. 在“创建 Azure Cosmos DB 帐户”页上,输入新 Azure Cosmos 帐户的基本设置。On the Create Azure Cosmos DB Account page, enter the basic settings for the new Azure Cosmos account.

    设置Setting Value DescriptionDescription
    订阅Subscription 订阅名称Subscription name 选择要用于此 Azure Cosmos 帐户的 Azure 订阅。Select the Azure subscription that you want to use for this Azure Cosmos account.
    资源组Resource Group 资源组名称Resource group name 选择一个资源组,或者选择“新建”,然后输入新资源组的唯一名称。Select a resource group, or select Create new, then enter a unique name for the new resource group.
    帐户名Account Name 输入唯一的名称Enter a unique name 输入标识此 Azure Cosmos 帐户的名称。Enter a name to identify your Azure Cosmos account. 由于 documents.azure.cn 字符串将追加到所提供的 ID 后面以创建 URI,因此,请使用唯一的 ID。Because documents.azure.cn is appended to the ID that you provide to create your URI, use a unique ID.

    ID 只能包含小写字母、数字和连字符 (-) 字符。The ID can only contain lowercase letters, numbers, and the hyphen (-) character. 它的长度必须介于 3 到 31 个字符之间。It must be between 3-31 characters in length.
    APIAPI Core (SQL)Core (SQL) API 确定要创建的帐户的类型。The API determines the type of account to create. Azure Cosmos DB 提供五种 API:适用于文档数据的 Core (SQL) 和 MongoDB、适用于图形数据的 Gremlin、Azure 表和 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) and MongoDB for document data, Gremlin for graph data, Azure Table, and Cassandra. 目前,你必须为每种 API 创建单独的帐户。Currently, you must create a separate account for each API.

    选择“Core (SQL)”,以便使用 SQL 语法创建文档数据库并进行查询。Select Core (SQL) to create a document database and query by using SQL syntax.

    详细了解 SQL APILearn more about the SQL API.
    位置Location 选择离用户最近的区域Select the region closest to your users 选择用于托管 Azure Cosmos DB 帐户的地理位置。Select a geographic location to host your Azure Cosmos DB account. 使用离用户最近的位置,使他们能够以最快的速度访问数据。Use the location that is closest to your users to give them the fastest access to the data.

    Azure Cosmos DB 的“新建帐户”页

  4. 选择“查看 + 创建”。Select Review + create. 可以跳过“网络”和“标记”部分。You can skip the Network and Tags sections.

  5. 检查帐户设置,然后选择“创建”。Review the account settings, and then select Create. 创建帐户需要几分钟时间。It takes a few minutes to create the account. 等待门户页显示“你的部署已完成”消息。Wait for the portal page to display Your deployment is complete.

    Azure 门户“通知”窗格

  6. 选择“转到资源”,转到 Azure Cosmos DB 帐户页。Select Go to resource to go to the Azure Cosmos DB account page.

    Azure Cosmos DB 帐户页

现在导航到“Azure Cosmos DB 帐户”页,单击“键”,因为我们在下一步创建的 Web 应用程序中使用这些值。Now navigate to the Azure Cosmos DB account page, and click Keys, as these values are used in the web application you create next.

Azure 门户的 Azure Cosmos DB 帐户页上突出显示“密钥”按钮的屏幕截图


现在,我们演练如何从头开始创建新的 ASP.NET MVC 应用程序。We will now walk through how to create a new ASP.NET MVC application from the ground-up.

步骤 2:新建 ASP.NET MVC 应用程序Step 2: Create a new ASP.NET MVC application

  1. 在 Visual Studio 的“文件”菜单中,指向“新建”,并单击“项目”。In Visual Studio, on the File menu, point to New, and then click Project. 将显示“新建项目”对话框。The New Project dialog box appears.

  2. 在“项目类型”窗格中,依次展开“模板”、“Visual C#”、“Web”,并选择“ASP.NET Web 应用程序”。In the Project types pane, expand Templates, Visual C#, Web, and then select ASP.NET Web Application.

    “新建项目”对话框的屏幕截图,突出显示了 ASP.NET Web 应用程序项目类型

  3. 在“名称”框中,键入项目的名称。In the Name box, type the name of the project. 本教程使用名称“todo”。This tutorial uses the name "todo". 如果选择使用其他名称,则每当本教程提及 todo 命名空间时,必须调整所提供的代码示例,以便使用为应用程序命名的名称。If you choose to use something other than this, then wherever this tutorial talks about the todo namespace, you need to adjust the provided code samples to use whatever you named your application.

  4. 单击“浏览”导航到要在其中创建项目的文件夹,并单击“确定”。Click Browse to navigate to the folder where you would like to create the project, and then click OK.

    将出现“新建 ASP.NET Web 应用程序”对话框。The New ASP.NET Web Application dialog box appears.

    “新建 ASP.NET Web 应用程序”对话框的屏幕截图,突出显示了 MVC 应用程序模板

  5. 在模板窗格中,选择“MVC”。In the templates pane, select MVC.

  6. 单击“确定”,让 Visual Studio 围绕空白 ASP.NET MVC 模板基架的搭建执行操作。Click OK and let Visual Studio do its thing around scaffolding the empty ASP.NET MVC template.

  7. Visual Studio 创建好样板 MVC 应用程序之后,便拥有可以在本地运行的空白 ASP.NET 应用程序。Once Visual Studio has finished creating the boilerplate MVC application you have an empty ASP.NET application that you can run locally.

    我们会跳过在本地运行项目,因为我确定我们都已看过 ASP.NET“Hello World”应用程序。We'll skip running the project locally because I'm sure we've all seen the ASP.NET "Hello World" application. 让我们直接跳到将 Azure Cosmos DB 添加到此项目并构建应用程序的步骤。Let's go straight to adding Azure Cosmos DB to this project and building our application.

步骤 3:将 Azure Cosmos DB 添加到 MVC Web 应用程序项目Step 3: Add Azure Cosmos DB to your MVC web application project

完成此解决方案的大部分 ASP.NET MVC 琐事后,可以开始本教程的真正目的,也就是将 Azure Cosmos DB 添加到 MVC Web 应用程序。Now that we have most of the ASP.NET MVC plumbing that we need for this solution, let's get to the real purpose of this tutorial, adding Azure Cosmos DB to our MVC web application.

  1. Azure Cosmos DB .NET SDK 将打包并以 NuGet 包的形式分发。The Azure Cosmos DB .NET SDK is packaged and distributed as a NuGet package. 若要在 Visual Studio 中获取 NuGet 包,请使用 Visual Studio 中的 NuGet 包管理器,方法是右键单击“解决方案资源管理器”中的项目,并单击“管理 NuGet 包”。To get the NuGet package in Visual Studio, use the NuGet package manager in Visual Studio by right-clicking on the project in Solution Explorer and then clicking Manage NuGet Packages.

    屏幕截图:解决方案资源管理器中 Web 应用程序项目的右键单击选项,突出显示了“管理 NuGet 包”。

    此时显示“管理 NuGet 包”对话框 。The Manage NuGet Packages dialog box appears.

  2. 在 NuGet“浏览”框中,键入 Azure DocumentDBIn the NuGet Browse box, type Azure DocumentDB. (包名称尚未更新为 Azure Cosmos DB。)(The package name has not been updated to Azure Cosmos DB.)

    从结果中安装“Microsoft 提供的 Microsoft.Azure.DocumentDB”包。From the results, install the Microsoft.Azure.DocumentDB by Microsoft package. 这会下载并安装 Azure Cosmos DB 程序包,以及所有依赖项(例如 Newtonsoft.Json)。This will download and install the Azure Cosmos DB package as well as all dependencies, such as Newtonsoft.Json. 在“预览”窗口中单击“确定”,并在“许可证接受”窗口中单击“我接受”,以完成安装。Click OK in the Preview window, and I Accept in the License Acceptance window to complete the install.

    “管理 NuGet 包”窗口的屏幕截图,突出显示了 Azure Cosmos DB 客户端库

    或者,也可以使用程序包管理器控制台来安装程序包。Alternatively you can use the Package Manager Console to install the package. 为此,请在“工具”菜单中,单击“NuGet 包管理器”,并单击“包管理器控制台”。To do so, on the Tools menu, click NuGet Package Manager, and then click Package Manager Console. 在提示符处键入以下命令。At the prompt, type the following.

     Install-Package Microsoft.Azure.DocumentDB
    
  3. 安装程序包之后,Visual Studio 解决方案应该类似于下列添加了两个新引用(Microsoft.Azure.Documents.Client 和 Newtonsoft.Json)的解决方案。Once the package is installed, your Visual Studio solution should resemble the following with two new references added, Microsoft.Azure.Documents.Client and Newtonsoft.Json.

    屏幕截图:解决方案资源管理器中添加到 JSON 数据项目的两个引用

步骤 4:设置 ASP.NET MVC 应用程序Step 4: Set up the ASP.NET MVC application

现在我们可以开始向此 MVC 应用程序添加模型、视图和控制器:Now let's add the models, views, and controllers to this MVC application:

添加 JSON 数据模型Add a JSON data model

首先,让我们在 MVC 中创建 M (模型)。Let's begin by creating the M in MVC, the model.

  1. 在“解决方案资源管理器”中,右键单击“模型”文件夹,单击“添加”,并单击“类”。In Solution Explorer, right-click the Models folder, click Add, and then click Class.

    此时会显示“添加新项”对话框。The Add New Item dialog box appears.

  2. 将新类命名为 Item.cs,并单击“添加”。Name your new class Item.cs and click Add.

  3. 在这个新的 Item.cs 文件中,将下列代码添加到最后一个 using 语句后面。In this new Item.cs file, add the following after the last using statement.

     using Newtonsoft.Json;
    
  4. 现在将此代码Now replace this code

     public class Item
     {
     }
    

    替换为以下代码。with the following code.

     public class Item
     {
         [JsonProperty(PropertyName = "id")]
         public string Id { get; set; }
    
         [JsonProperty(PropertyName = "name")]
         public string Name { get; set; }
    
         [JsonProperty(PropertyName = "description")]
         public string Description { get; set; }
    
         [JsonProperty(PropertyName = "isComplete")]
         public bool Completed { get; set; }
     }
    

    Azure Cosmos DB 中的所有数据都会通过线路传递,并存储为 JSON。All data in Azure Cosmos DB is passed over the wire and stored as JSON. 若要通过 JSON.NET 控制对象的序列化/反序列化方式,可以使用刚才创建的 Item 类中所示的 JsonProperty 属性。To control the way your objects are serialized/deserialized by JSON.NET you can use the JsonProperty attribute as demonstrated in the Item class we just created. 不一定 要这样做,但我想确保所有属性都按照 JSON camelCase 命名约定命名。You don't have to do this but I want to ensure that my properties follow the JSON camelCase naming conventions.

    使用 JSON 时,不但可以控制属性名称的格式,还可以像我命名 Description 属性一样重命名 .NET 属性。Not only can you control the format of the property name when it goes into JSON, but you can entirely rename your .NET properties like I did with the Description property.

添加控制器Add a controller

现已创建 M,接下来创建 MVC 中的 C(控制器类)。That takes care of the M, now let's create the C in MVC, a controller class.

  1. 在“解决方案资源管理器”中,右键单击“控制器”文件夹,单击“添加”,并单击“控制器”。In Solution Explorer, right-click the Controllers folder, click Add, and then click Controller.

    此时会显示“添加基架”对话框。The Add Scaffold dialog box appears.

  2. 选择“MVC 5 控制器 - 空”,并单击“添加”。Select MVC 5 Controller - Empty and then click Add.

    “添加基架”对话框的屏幕截图,突出显示了“MVC 5 控制器 - 空”选项

  3. 将新控制器命名为 ItemControllerName your new Controller, ItemController.

    屏幕截图:“添加控制器”对话框

    创建文件之后,Visual Studio 解决方案应该类似于下列在“解决方案资源管理器”中包含有新 ItemController.cs 文件的解决方案。Once the file is created, your Visual Studio solution should resemble the following with the new ItemController.cs file in Solution Explorer. 系统还会显示先前创建的新 Item.cs 文件。The new Item.cs file created earlier is also shown.

    “Visual Studio 解决方案 - 解决方案资源管理器”的屏幕截图,突出显示了新的 ItemController.cs 文件和 Item.cs 文件

    可以关闭 ItemController.cs,我们稍后会回头使用此文件。You can close ItemController.cs, we'll come back to it later.

添加视图Add views

现在,我们可以开始创建 MVC 中的 V (视图):Now, let's create the V in MVC, the views:

添加“项索引”视图Add an Item Index view

  1. 在“解决方案资源管理器”中,展开“视图”文件夹,右键单击先前在添加 ItemController 时 Visual Studio 创建的空白“项”文件夹,单击“添加”,并单击“视图”。In Solution Explorer, expand the Views folder, right-click the empty Item folder that Visual Studio created for you when you added the ItemController earlier, click Add, and then click View.

    解决方案资源管理器的屏幕截图,显示 Visual Studio 创建的 Item 文件夹,并且突出显示了“添加视图”命令

  2. 在“添加视图”对话框中,执行以下操作: In the Add View dialog box, do the following:

    • 在“视图名称”框中,键入“索引”。In the View name box, type Index.
    • 在“模板”框中,选择“列表”。In the Template box, select List.
    • 在“模型类”框中,选择“项(todo.Models)”。In the Model class box, select Item (todo.Models).
    • 在“布局页”框中,键入 ~/Views/Shared/_Layout.cshtmlIn the layout page box, type ~/Views/Shared/_Layout.cshtml.

    屏幕截图:显示“添加视图”对话框

  3. 设置完所有这些值之后,单击“添加”,让 Visual Studio 创建新的模板视图。Once all these values are set, click Add and let Visual Studio create a new template view. 完成之后,它会打开刚创建的 cshtml 文件。Once it is done, it will open the cshtml file that was created. 我们可以在 Visual Studio 中关闭该文件,我们稍后会回头使用此文件。We can close that file in Visual Studio as we will come back to it later.

添加“新建项”视图Add a New Item view

与创建“项索引”视图的方式类似,我们现在可以开始创建新的视图,以供创建新使用。Similar to how we created an Item Index view, we will now create a new view for creating new Items.

  1. 在“解决方案资源管理器”中,再次右键单击“Item”文件夹,单击“添加”,并单击“视图”。In Solution Explorer, right-click the Item folder again, click Add, and then click View.

  2. 在“添加视图”对话框中,执行以下操作: In the Add View dialog box, do the following:

    • 在“视图名称”框中,键入“创建”。In the View name box, type Create.
    • 在“模板”框中,选择“创建”。In the Template box, select Create.
    • 在“模型类”框中,选择“项(todo.Models)”。In the Model class box, select Item (todo.Models).
    • 在“布局页”框中,键入 ~/Views/Shared/_Layout.cshtmlIn the layout page box, type ~/Views/Shared/_Layout.cshtml.
    • 单击“添加” 。Click Add.

添加“编辑项”视图Add an Edit Item view

最后,采用与之前相同的方式添加最后一个视图,以供编辑 使用。And finally, add one last view for editing an Item in the same way as before.

  1. 在“解决方案资源管理器”中,再次右键单击“Item”文件夹,单击“添加”,并单击“视图”。In Solution Explorer, right-click the Item folder again, click Add, and then click View.

  2. 在“添加视图”对话框中,执行以下操作: In the Add View dialog box, do the following:

    • 在“视图名称”框中,键入“编辑”。In the View name box, type Edit.
    • 在“模板”框中,选择“编辑”。In the Template box, select Edit.
    • 在“模型类”框中,选择“项(todo.Models)”。In the Model class box, select Item (todo.Models).
    • 在“布局页”框中,键入 ~/Views/Shared/_Layout.cshtmlIn the layout page box, type ~/Views/Shared/_Layout.cshtml.
    • 单击“添加”。Click Add.

完成此操作之后,关闭 Visual Studio 中的所有 cshtml 文档,我们稍后会回头使用这些视图。Once this is done, close all the cshtml documents in Visual Studio as we will return to these views later.

步骤 5:连接 Azure Cosmos DBStep 5: Wiring up Azure Cosmos DB

我们已经创建了标准的 MVC 项目,现在我们可以开始添加 Azure Cosmos DB 的代码。Now that the standard MVC stuff is taken care of, let's turn to adding the code for Azure Cosmos DB.

在本节中,我们将添加代码来处理下列操作:In this section, we'll add code to handle the following:

列出 MVC Web 应用程序中未完成的项Listing incomplete Items in your MVC web application

首先要执行的操作是添加类,其中包含要连接并使用 Azure Cosmos DB 的所有逻辑。The first thing to do here is add a class that contains all the logic to connect to and use Azure Cosmos DB. 在本教程中,我们会将所有逻辑封装到名为 DocumentDBRepository 的存储库类中。For this tutorial we'll encapsulate all this logic in to a repository class called DocumentDBRepository.

  1. 在“解决方案资源管理器”中,右键单击该项目,并依次单击“添加”、“类”。In Solution Explorer, right-click on the project, click Add, and then click Class. 将新类命名为 DocumentDBRepository,并单击“添加”。Name the new class DocumentDBRepository and click Add.

  2. 在刚刚创建的 DocumentDBRepository 类中,在命名空间声明上方添加以下 using 语句In the newly created DocumentDBRepository class and add the following using statements above the namespace declaration

     using Microsoft.Azure.Documents; 
     using Microsoft.Azure.Documents.Client; 
     using Microsoft.Azure.Documents.Linq; 
     using System.Configuration;
     using System.Linq.Expressions;
     using System.Threading.Tasks;
     using System.Net;
    

    现在将此代码Now replace this code

     public class DocumentDBRepository
     {
     }
    

    替换为以下代码。with the following code.

     public static class DocumentDBRepository<T> where T : class
     {
         private static readonly string DatabaseId = ConfigurationManager.AppSettings["database"];
         private static readonly string CollectionId = ConfigurationManager.AppSettings["collection"];
         private static DocumentClient client;
    
         public static void Initialize()
         {
             client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]);
             CreateDatabaseIfNotExistsAsync().Wait();
             CreateCollectionIfNotExistsAsync().Wait();
         }
    
         private static async Task CreateDatabaseIfNotExistsAsync()
         {
             try
             {
                 await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId));
             }
             catch (DocumentClientException e)
             {
                 if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
                 {
                     await client.CreateDatabaseAsync(new Database { Id = DatabaseId });
                 }
                 else
                 {
                     throw;
                 }
             }
         }
    
         private static async Task CreateCollectionIfNotExistsAsync()
         {
             try
             {
                 await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId));
             }
             catch (DocumentClientException e)
             {
                 if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
                 {
                     await client.CreateDocumentCollectionAsync(
                         UriFactory.CreateDatabaseUri(DatabaseId),
                         new DocumentCollection { Id = CollectionId },
                         new RequestOptions { OfferThroughput = 1000 });
                 }
                 else
                 {
                     throw;
                 }
             }
         }
     }
    
  3. 我们打算从配置中读取部分值,因此请打开应用程序的 Web.config 文件,并在 <AppSettings> 节下面添加下列几行。We're reading some values from configuration, so open the Web.config file of your application and add the following lines under the <AppSettings> section.

     <add key="endpoint" value="enter the URI from the Keys blade of the Azure Portal"/>
     <add key="authKey" value="enter the PRIMARY KEY, or the SECONDARY KEY, from the Keys blade of the Azure  Portal"/>
     <add key="database" value="ToDoList"/>
     <add key="collection" value="Items"/>
    
  4. 现在,使用 Azure 门户的“密钥”边栏选项卡来更新终结点authKey 的值。Now, update the values for endpoint and authKey using the Keys blade of the Azure Portal. 使用“密钥”边栏选项卡中的“URI”作为终结点设置的值,使用“密钥”边栏选项卡中的“主密钥”或“辅助密钥”作为 authKey 设置的值。Use the URI from the Keys blade as the value of the endpoint setting, and use the PRIMARY KEY, or SECONDARY KEY from the Keys blade as the value of the authKey setting.

    我们已经连接了 Azure Cosmos DB 存储库,现在让我们添加应用程序逻辑。That takes care of wiring up the Azure Cosmos DB repository, now let's add our application logic.

  5. 我们想要用待办事项列表应用程序做的第一件事就是显示未完成的项。The first thing we want to be able to do with a todo list application is to display the incomplete items. DocumentDBRepository 类中的任意位置复制并粘贴以下代码片段。Copy and paste the following code snippet anywhere within the DocumentDBRepository class.

     public static async Task<IEnumerable<T>> GetItemsAsync(Expression<Func<T, bool>> predicate)
     {
         IDocumentQuery<T> query = client.CreateDocumentQuery<T>(
             UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId))
             .Where(predicate)
             .AsDocumentQuery();
    
         List<T> results = new List<T>();
         while (query.HasMoreResults)
         {
             results.AddRange(await query.ExecuteNextAsync<T>());
         }
    
         return results;
     }
    
  6. 打开我们先前添加的 ItemController ,并在命名空间声明上方添加以下 using 语句Open the ItemController we added earlier and add the following using statements above the namespace declaration.

     using System.Net;
     using System.Threading.Tasks;
     using todo.Models;
    

    如果项目名称不是“todo”,则必须使用“todo. Models”进行更新,才能反映项目名称。If your project is not named "todo", then you need to update using "todo.Models"; to reflect the name of your project.

    现在将此代码Now replace this code

     //GET: Item
     public ActionResult Index()
     {
         return View();
     }
    

    替换为以下代码。with the following code.

     [ActionName("Index")]
     public async Task<ActionResult> IndexAsync()
     {
         var items = await DocumentDBRepository<Item>.GetItemsAsync(d => !d.Completed);
         return View(items);
     }
    
  7. 打开 Global.asax.cs 并将以下行添加到 Application_Start 方法Open Global.asax.cs and add the following line to the Application_Start method

     DocumentDBRepository<todo.Models.Item>.Initialize();
    

此时,应该可以构建解决方案,而不会发生任何错误。At this point your solution should be able to build without any errors.

如果现在运行应用程序,则可转到 HomeController 以及该控制器的“索引”视图。If you ran the application now, you would go to the HomeController and the Index view of that controller. 这是我们一开始就选定的 MVC 模板项目默认行为,但是我们不想要这样的行为!This is the default behavior for the MVC template project we chose at the start but we don't want that! 让我们更改此 MVC 应用程序上的路由以改变此行为。Let's change the routing on this MVC application to alter this behavior.

打开 App_Start\RouteConfig.cs,找到以“defaults:”开头的行,并将它更改为如下行。Open App_Start\RouteConfig.cs and locate the line starting with "defaults:" and change it to resemble the following.

    defaults: new { controller = "Item", action = "Index", id = UrlParameter.Optional }

若未在 URL 中指定控制路由行为的值,这会让 ASP.NET MVC 知道改用“项”(而不是“主页”)作为控制器,并使用“索引”作为视图。This now tells ASP.NET MVC that if you have not specified a value in the URL to control the routing behavior that instead of Home, use Item as the controller and user Index as the view.

若运行应用程序,它现在会调用到 ItemController,进而调用到存储库类,并使用 GetItems 方法将所有未完成的项返回到“视图\项\索引”视图。Now if you run the application, it will call into your ItemController which will call in to the repository class and use the GetItems method to return all the incomplete items to the Views\Item\Index view.

如果构建并立即运行此项目,现在应该会看到如下内容。If you build and run this project now, you should now see something that looks this.

屏幕截图:本数据库教程创建的待办事项列表 Web 应用程序

添加项Adding Items

我们可以开始将一些项放入数据库中,所以除了空白网格以外,我们还可以看到其他内容。Let's put some items into our database so we have something more than an empty grid to look at.

让我们将一些代码添加到 Azure Cosmos DBRepository 和 ItemController,以在 Azure Cosmos DB 中持久保存记录。Let's add some code to Azure Cosmos DBRepository and ItemController to persist the record in Azure Cosmos DB.

  1. 将下列方法添加到 DocumentDBRepository 类。Add the following method to your DocumentDBRepository class.

    public static async Task<Document> CreateItemAsync(T item)
    {
        return await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), item);
    }
    

    此方法只接受传递给它的对象,并将对象保留在 Azure Cosmos DB 中。This method simply takes an object passed to it and persists it in Azure Cosmos DB.

  2. 打开 ItemController.cs 文件,并在类中添加下列代码段。Open the ItemController.cs file and add the following code snippet within the class. 这是 ASP.NET MVC 得知如何执行 创建 操作的方式。This is how ASP.NET MVC knows what to do for the Create action. 在此情况下,只需呈现先前创建的关联 Create.cshtml 视图。In this case just render the associated Create.cshtml view created earlier.

     [ActionName("Create")]
     public async Task<ActionResult> CreateAsync()
     {
         return View();
     }
    

    现在此控制器需要更多代码,以接受“创建”视图所提交的数据。We now need some more code in this controller that will accept the submission from the Create view.

  3. 将下一个代码块添加到 ItemController.cs 类,以告诉 ASP.NET MVC 如何使用窗体 POST 来执行此控制器的操作。Add the next block of code to the ItemController.cs class that tells ASP.NET MVC what to do with a form POST for this controller.

     [HttpPost]
     [ActionName("Create")]
     [ValidateAntiForgeryToken]
     public async Task<ActionResult> CreateAsync([Bind(Include = "Id,Name,Description,Completed")] Item item)
     {
         if (ModelState.IsValid)
         {
             await DocumentDBRepository<Item>.CreateItemAsync(item);
             return RedirectToAction("Index");
         }
    
         return View(item);
     }
    

    此代码会调用到 DocumentDBRepository,并使用 CreateItemAsync 方法将新的待办事项保存到数据库。This code calls in to the DocumentDBRepository and uses the CreateItemAsync method to persist the new todo item to the database.

    安全说明:此处使用的 ValidateAntiForgeryToken 属性可帮助此应用程序防止跨站点请求伪造攻击。Security Note: The ValidateAntiForgeryToken attribute is used here to help protect this application against cross-site request forgery attacks. 这不仅仅是添加此属性,视图也必须使用此防伪令牌。There is more to it than just adding this attribute, your views need to work with this anti-forgery token as well. 有关此主题的详细信息以及如何正确实施此操作的示例,请参阅 防止跨站点请求伪造For more on the subject, and examples of how to implement this correctly, please see Preventing Cross-Site Request Forgery. GitHub 上提供的源代码已有完整实现。The source code provided on GitHub has the full implementation in place.

    安全说明:我们还会在方法参数中使用 Bind 属性,帮助防范过度提交攻击。Security Note: We also use the Bind attribute on the method parameter to help protect against over-posting attacks. 有关更多详细信息,请参阅 ASP.NET MVC 中的基本 CRUD 操作For more details please see Basic CRUD Operations in ASP.NET MVC.

将新项添加到数据库所需的代码至此结束。This concludes the code required to add new Items to our database.

编辑项Editing Items

我们最后还要做一件事,那就是添加在数据库中编辑并将它们标记为已完成的功能。There is one last thing for us to do, and that is to add the ability to edit Items in the database and to mark them as complete. 编辑视图已添加到项目中,因此,我们只需重新将某些代码添加到控制器和 DocumentDBRepository 类。The view for editing was already added to the project, so we just need to add some code to our controller and to the DocumentDBRepository class again.

  1. 将下列代码添加到 DocumentDBRepository 类。Add the following to the DocumentDBRepository class.

     public static async Task<Document> UpdateItemAsync(string id, T item)
     {
         return await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), item);
     }
    
     public static async Task<T> GetItemAsync(string id)
     {
         try
         {
             Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id));
             return (T)(dynamic)document;
         }
         catch (DocumentClientException e)
         {
             if (e.StatusCode == HttpStatusCode.NotFound)
             {
                 return null;
             }
             else
             {
                 throw;
             }
         }
     }
    

    这些方法中的第一个方法 (GetItem) 会从 Azure Cosmos DB 中提取某个项,此项会被传递回 ItemController,接着传到“编辑”视图。The first of these methods, GetItem fetches an Item from Azure Cosmos DB which is passed back to the ItemController and then on to the Edit view.

    刚刚添加的第二个方法使用从 ItemController 传入的文档版本取代 Azure Cosmos DB 中的文档The second of the methods we just added replaces the Document in Azure Cosmos DB with the version of the Document passed in from the ItemController.

  2. 将下列代码添加到 ItemController 类。Add the following to the ItemController class.

     [HttpPost]
     [ActionName("Edit")]
     [ValidateAntiForgeryToken]
     public async Task<ActionResult> EditAsync([Bind(Include = "Id,Name,Description,Completed")] Item item)
     {
         if (ModelState.IsValid)
         {
             await DocumentDBRepository<Item>.UpdateItemAsync(item.Id, item);
             return RedirectToAction("Index");
         }
    
         return View(item);
     }
    
     [ActionName("Edit")]
     public async Task<ActionResult> EditAsync(string id)
     {
         if (id == null)
         {
             return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
         }
    
         Item item = await DocumentDBRepository<Item>.GetItemAsync(id);
         if (item == null)
         {
             return HttpNotFound();
         }
    
         return View(item);
     }
    

    第一个方法会处理当用户单击“索引”视图中的“编辑”链接时所发生的 Http GET。The first method handles the Http GET that happens when the user clicks on the Edit link from the Index view. 此方法会从 Azure Cosmos DB 中提取文档,并将它传递给“编辑”视图。This method fetches a Document from Azure Cosmos DB and passes it to the Edit view.

    “编辑”视图会接着对 IndexController 执行 Http POST 操作。The Edit view will then do an Http POST to the IndexController.

    添加的第二个方法会处理此操作:将更新对象传递到 Azure Cosmos DB 以便持久保存在数据库中。The second method we added handles passing the updated object to Azure Cosmos DB to be persisted in the database.

这样便大功告成了,这些就是我们必须运行应用程序的所有操作:列出未完成的,添加新,最后是编辑That's it, that is everything we need to run our application, list incomplete Items, add new Items, and edit Items.

步骤 6:在本地运行应用程序Step 6: Run the application locally

若要在本地计算机上测试应用程序,请执行以下操作:To test the application on your local machine, do the following:

  1. 在 Visual Studio 中按 F5,即可在调试模式下构建应用程序。Hit F5 in Visual Studio to build the application in debug mode. 这样应该可以构建应用程序,并启动包含先前看到的空白网格页面的浏览器:It should build the application and launch a browser with the empty grid page we saw before:

    屏幕截图:本数据库教程创建的待办事项列表 Web 应用程序

  2. 单击“新建”链接,并在“名称”和“说明”字段中添加值。Click the Create New link and add values to the Name and Description fields. 将“已完成”复选框保持为未选中状态,否则,新将以已完成状态添加,不会出现在初始列表中。Leave the Completed check box unselected otherwise the new Item will be added in a completed state and will not appear on the initial list.

    屏幕截图:“创建”视图

  3. 单击“创建”,随后将重定向回到“索引”视图,创建的会出现在列表中。Click Create and you are redirected back to the Index view and your Item appears in the list.

    屏幕截图:“索引”视图

    向待办事项列表任意添加更多 Feel free to add a few more Items to your todo list.

  4. 单击列表上某个旁边的“编辑”将转到“编辑”视图,可以在此视图中更新对象的任何属性(包括“已完成”标志)。Click Edit next to an Item on the list and you are taken to the Edit view where you can update any property of your object, including the Completed flag. 如果标记“已完成”标志并单击“保存”,该将从未完成任务列表中删除。If you mark the Complete flag and click Save, the Item is removed from the list of incomplete tasks.

    屏幕截图:选中了“已完成”框的“索引”视图

  5. 完成应用测试后,按 Ctrl+F5 停止调试应用。Once you've tested the app, press Ctrl+F5 to stop debugging the app. 可以开始部署了!You're ready to deploy!

步骤 7:将应用程序部署到 Azure 应用服务Step 7: Deploy the application to Azure App Service

现在,已经拥有了可以使用 Azure Cosmos DB 正常工作的完整应用程序,接下来我们要将此 Web 应用部署到 Azure 应用服务。Now that you have the complete application working correctly with Azure Cosmos DB we're going to deploy this web app to Azure App Service.

  1. 若要发布此应用程序,只需要右键单击“解决方案资源管理器”中的项目,并单击“发布”即可。To publish this application all you need to do is right-click on the project in Solution Explorer and click Publish.

    屏幕截图:解决方案资源管理器中的“发布”选项

  2. 在“发布”对话框中,单击“Azure 应用服务”,然后选择“新建”以创建应用服务配置文件,或单击“选择现有项”使用现有配置文件。In the Publish dialog box, click Azure App Service, then select Create New to create an App Service profile, or click Select Existing to use an existing profile.

    Visual Studio 中的“发布”对话框

  3. 如果具有现有的 Azure 应用服务配置文件,请输入订阅名称。If you have an existing Azure App Service profile, enter your subscription name. 使用“视图”按资源组或资源类型进行筛选,然后选择 Azure 应用服务。Use the View filter to sort by resource group or resource type, then select your Azure App Service.

    Visual Studio 中的“应用服务”对话框

  4. 若要创建新的 Azure 应用服务配置文件,请单击“发布”对话框中的“新建”。To create a new Azure App Service profile, click Create New in the Publish dialog box. 在“创建应用服务”对话框中,输入 Web 应用名称和相应的订阅、资源组和应用服务计划,然后单击“创建”。In the Create App Service dialog, enter your Web App name and appropriate subscription, resource group, and App Service plan, then click Create.

    Visual Studio 中的“创建应用服务”对话框

在几秒钟内,Visual Studio 将完成 Web 应用程序发布并启动浏览器,可从中查看在 Azure 中运行的简单作品!In a few seconds, Visual Studio will finish publishing your web application and launch a browser where you can see your handiwork running in Azure!

后续步骤Next steps

祝贺!Congratulations! 刚才构建了第一个使用 Azure Cosmos DB 的 ASP.NET MVC Web 应用程序并将其发布到了 Azure。You just built your first ASP.NET MVC web application using Azure Cosmos DB and published it to Azure. 可以从 GitHub 下载或克隆完整应用程序(包括本教程未涵盖的详细信息和删除功能)的源代码。The source code for the complete application, including the detail and delete functionality that were not included in this tutorial can be downloaded or cloned from GitHub. 因此,如果想将代码添加到应用中,请捕捉代码,再将它添加到此应用中。So if you're interested in adding that to your app, grab the code and add it to this app.

若要向应用程序添加其他功能,请查看 Azure Cosmos DB .NET 库中提供的 API,并欢迎在 GitHub 上的 Azure Cosmos DB .NET 库中补充内容。To add additional functionality to your application, review the APIs available in the Azure Cosmos DB .NET Library and feel free to contribute to the Azure Cosmos DB .NET Library on GitHub.