教程:通过 .NET SDK 开发使用 Azure Cosmos DB 的 ASP.NET Core MVC Web 应用程序Tutorial: Develop an ASP.NET Core MVC web application with Azure Cosmos DB by using .NET SDK

本教程介绍如何使用 Azure Cosmos DB 通过 Azure 上托管的 ASP.NET MVC 应用程序存储和访问数据。This tutorial shows you how to use Azure Cosmos DB to store and access data from an ASP.NET MVC application that is hosted on Azure. 在本教程中,请使用 .NET SDK V3。In this tutorial, you use the .NET SDK V3. 下图显示将要使用本文中的示例生成的网页:The following image shows the web page that you'll build by using the sample in this article:

按本教程(ASP NET Core MVC 分步教程)创建的待办事项列表 MVC Web 应用程序的屏幕截图

如果没有时间完成本教程,可以从 GitHub 下载完整的示例项目。If you don't have time to complete the tutorial, you can download the complete sample project from GitHub.

本教程涉及:This tutorial covers:

  • 创建 Azure Cosmos 帐户Creating an Azure Cosmos account
  • 创建 ASP.NET Core MVC 应用Creating an ASP.NET Core MVC app
  • 将应用连接到 Azure Cosmos DBConnecting the app to Azure Cosmos DB
  • 对数据执行创建、读取、更新和删除 (CRUD) 操作Performing create, read, update, and delete (CRUD) operations on the data

提示

本教程假定你先前有使用 ASP.NET Core MVC 和 Azure 应用服务的经验。This tutorial assumes that you have prior experience using ASP.NET Core MVC and Azure App Service. 如果你不熟悉 ASP.NET Core 或必备工具,我们建议从 GitHub 下载完整的示例项目,然后添加所需的 NuGet 包并运行它。If you are new to ASP.NET Core or the prerequisite tools, we recommend you to download the complete sample project from GitHub, add the required NuGet packages, and run it. 生成项目之后,可以回顾本文以深入了解项目上下文中的代码。Once you build the project, you can review this article to gain insight on the code in the context of the project.

先决条件Prerequisites

在按照本文中的说明操作之前,请确保具备以下资源:Before following the instructions in this article, make sure that you have the following resources:

本文中的所有屏幕截图都是在 Microsoft Visual Studio Community 2019 中截取的。All the screenshots in this article are from Microsoft Visual Studio Community 2019. 如果你使用其他版本,则屏幕截图和选项可能不与此完全相同。If you use a different version, your screens and options may not match entirely. 如果满足先决条件,解决方案应可正常运行。The solution should work if you meet the prerequisites.

步骤 1:创建 Azure Cosmos 帐户Step 1: Create an Azure Cosmos account

让我们首先创建一个 Azure Cosmos 帐户。Let's start by creating an Azure Cosmos account. 如果你已有一个 Azure Cosmos DB SQL API 帐户,或者使用的是 Azure Cosmos DB 仿真器,请跳到步骤 2:创建新的 ASP.NET MVC 应用程序If you already have an Azure Cosmos DB SQL API account or if you're using the Azure Cosmos DB emulator, skip to Step 2: Create a new ASP.NET MVC application.

  1. 在 Azure 门户菜单或主页中,选择“创建资源” 。From the Azure portal menu or the Home page, select Create a resource.

  2. 在“新建”页面中搜索“Azure Cosmos DB”,然后选择它。 On the New page, search for and select Azure Cosmos DB.

  3. 在“Azure Cosmos DB”页上,选择“创建”。On the Azure Cosmos DB page, select Create.

  4. 在“创建 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 说明Description
    订阅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 唯一的名称A unique name 输入标识此 Azure Cosmos 帐户的名称。Enter a name to identify your Azure Cosmos account. 由于 documents.azure.cn 将追加到所提供的名称以创建 URI,因此,请使用唯一的名称**。Because documents.azure.cn is appended to the name that you provide to create your URI, use a unique name.

    名称只能包含小写字母、数字和连字符 (-)。The name can only contain lowercase letters, numbers, and the hyphen (-) character. 它的长度必须介于 3-44 个字符之间。It must be between 3-44 characters in length.
    APIAPI 要创建的帐户的类型The type of account to create 选择“Core (SQL)”,以便使用 SQL 语法创建文档数据库并进行查询。Select Core (SQL) to create a document database and query by using SQL syntax.

    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.
    应用免费层折扣Apply Free Tier Discount 应用或不应用Apply or Do not apply 使用 Azure Cosmos DB 免费层,你将在帐户中获得每秒的前 400 RU 免费的吞吐量和 5 GB 的免费存储。With Azure Cosmos DB free tier, you will get the first 400 RU/s and 5 GB of storage for free in an account. 了解免费层的详细信息。Learn more about free tier.
    位置Location 离用户最近的区域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.
    帐户类型Account Type 生产或非生产Production or Non-Production 如果帐户将用于生产工作负荷,请选择“生产”。Select Production if the account will be used for a production workload. 如果帐户将用于非生产环境(例如开发、测试、QA 或过渡),请选择“非生产”。Select Non-Production if the account will be used for non-production, e.g. development, testing, QA, or staging. 这是一个 Azure 资源标记设置,用于调整门户体验,但不会影响基础 Azure Cosmos DB 帐户。This is an Azure resource tag setting that tunes the Portal experience but does not affect the underlying Azure Cosmos DB account. 可以随时更改此值。You can change this value anytime.

    备注

    每个 Azure 订阅最多可以有一个免费层 Azure Cosmos DB 帐户,并且你必须在创建帐户时选择加入使用。You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. 如果看不到用于应用免费层折扣的选项,这意味着订阅中的另一个帐户已启用免费层。If you do not see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.

    Azure Cosmos DB 的“新建帐户”页面

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

  6. 检查帐户设置,然后选择“创建”。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 门户“通知”窗格

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

    Azure Cosmos DB 帐户页面

转到 Azure Cosmos DB 帐户页,并选择“密钥” 。Go to the Azure Cosmos DB account page, and select Keys. 复制要在下一步创建的 Web 应用程序中使用的值。Copy the values to use in the web application you create next.

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

在下一部分,将新建一个 ASP.NET Core MVC 应用程序。In the next section, you create a new ASP.NET Core MVC application.

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

  1. 打开 Visual Studio 并选择“创建新项目”。Open Visual Studio and select Create a new project.

  2. 在“创建新项目”中,找到并选择适用于 C# 的“ASP.NET Core Web 应用程序”。 In Create a new project, find and select ASP.NET Core Web Application for C#. 选择“下一步”继续。Select Next to continue.

    新建 ASP.NET Core Web 应用程序项目

  3. 在“配置新项目”中,将项目命名为 todo,然后选择“创建”。 In Configure your new project, name the project todo and select Create.

  4. 在“创建新的 ASP.NET Core Web 应用程序”中,选择“Web 应用程序(模型-视图-控制器)”。 In Create a new ASP.NET Core Web Application, choose Web Application (Model-View-Controller). 选择“创建”继续操作。Select Create to continue.

    Visual Studio 将创建一个空的 MVC 应用程序。Visual Studio creates an empty MVC application.

  5. 选择“调试” > “开始调试”或按 F5,在本地运行 ASP.NET 应用程序。 Select Debug > Start Debugging or F5 to run your ASP.NET application locally.

步骤 3:向项目添加 Azure Cosmos DB NuGet 包Step 3: Add Azure Cosmos DB NuGet package to the project

有了此解决方案所需的大多数 ASP.NET Core MVC 框架代码以后,即可添加连接到 Azure Cosmos DB 所需的 NuGet 包。Now that we have most of the ASP.NET Core MVC framework code that we need for this solution, let's add the NuGet packages required to connect to Azure Cosmos DB.

  1. 在“解决方案资源管理器”中,右键单击项目并选择“管理 NuGet 包”。 In Solution Explorer, right-click your project and select Manage NuGet Packages.

  2. 在“NuGet 包管理器”中,搜索并选择“Microsoft.Azure.Cosmos”。 In the NuGet Package Manager, search for and select Microsoft.Azure.Cosmos. 选择“安装”。Select Install.

    安装 NuGet 包

    Visual Studio 会下载并安装 Azure Cosmos DB 包及其依赖项。Visual Studio downloads and installs the Azure Cosmos DB package and its dependencies.

    你也可以使用“包管理器控制台”来安装 NuGet 包。You can also use Package Manager Console to install the NuGet package. 为此,请选择“工具” > “NuGet 包管理器” > “包管理器控制台”。 To do so, select Tools > NuGet Package Manager > Package Manager Console. 在提示符处键入以下命令:At the prompt, type the following command:

    Install-Package Microsoft.Azure.Cosmos
    

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

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

添加模型Add a model

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

  2. 在“添加新项”中,将新类命名为 Item.cs,然后选择“添加”。 In Add New Item, name your new class Item.cs and select Add.

  3. Item.cs 类的内容替换为以下代码:Replace the contents of Item.cs class with the following code:

    namespace todo.Models
    {
       using Newtonsoft.Json;
    
       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 来移动和存储数据。Azure Cosmos DB uses JSON to move and store data. 可以使用 JsonProperty 属性来控制 JSON 序列化和反序列化对象的方式。You can use the JsonProperty attribute to control how JSON serializes and deserializes objects. Item 类演示 JsonProperty 属性。The Item class demonstrates the JsonProperty attribute. 此代码控制进入 JSON 的属性名称的格式。This code controls the format of the property name that goes into JSON. 它还将 .NET 属性重命名为 CompletedIt also renames the .NET property Completed.

添加视图Add views

接下来,让我们添加以下视图。Next, let's add the following views.

  • 创建项视图A create item view
  • 删除项视图A delete item view
  • 用于获取项详细信息的视图A view to get an item details
  • 编辑项视图An edit item view
  • 用于列出所有项的视图A view to list all the items

创建项视图Create item view

  1. 在“解决方案资源管理器”中,右键单击“视图”文件夹并选择“添加” > “新建文件夹”。 In Solution Explorer, right-click the Views folder and select Add > New Folder. 将文件夹命名为“项”。Name the folder Item.

  2. 右键单击空的“项”文件夹,并选择“添加” > “视图”。 Right-click the empty Item folder, then select Add > View.

  3. 在“添加 MVC 视图”中进行以下更改:In Add MVC View, make the following changes:

    • 在“视图名称”中,输入“创建”。In View name, enter Create.
    • 在“模板”中选择“创建”。 In Template, select Create.
    • 在“模型类”中,选择“项(todo.Models)”。 In Model class, select Item (todo.Models).
    • 选择“使用布局页”并输入 ~/Views/Shared/_Layout.cshtmlSelect Use a layout page and enter ~/Views/Shared/_Layout.cshtml.
    • 选择 添加Select Add.

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

  4. 接下来,选择“添加”并让 Visual Studio 创建新的模板视图。Next select Add and let Visual Studio create a new template view. 将生成的文件中的代码替换为以下内容:Replace the code in the generated file with the following contents:

    @model todo.Models.Item
    
    @{
       ViewBag.Title = "Create";
       Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>Create a new To-Do Item</h2>
    
    @using (Html.BeginForm()) 
    {
       @Html.AntiForgeryToken()
    
       <div class="form-horizontal">
           <hr />
           @Html.ValidationSummary(true, "", new { @class = "text-danger" })
           <div class="form-group">
               @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
               <div class="col-md-10">
                   @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                   @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
               </div>
           </div>
    
           <div class="form-group">
               @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
               <div class="col-md-10">
                   @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
                   @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
               </div>
           </div>
    
           <div class="form-group">
               @Html.LabelFor(model => model.Completed, htmlAttributes: new { @class = "control-label col-md-2" })
               <div class="col-md-10">
                   <div class="checkbox">
                       @Html.EditorFor(model => model.Completed)
                       @Html.ValidationMessageFor(model => model.Completed, "", new { @class = "text-danger" })
                   </div>
               </div>
           </div>
    
           <div class="form-group">
               <div class="col-md-offset-2 col-md-10">
                   <input type="submit" value="Create" class="btn btn-default" />
               </div>
           </div>
       </div>
    }
    
    <div>
       @Html.ActionLink("Back to List", "Index")
    </div>
    <script src="~/bundles/jqueryval"></script>
    

删除项视图Delete item view

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

  2. 在“添加 MVC 视图”中进行以下更改:In Add MVC View, make the following changes:

    • 在“视图名称”框中键入“删除”。In the View name box, type Delete.
    • 在“模板”框中,选择“删除” 。In the Template box, select Delete.
    • 在“模型类”框中,选择“项(todo.Models)”。 In the Model class box, select Item (todo.Models).
    • 选择“使用布局页”并输入 ~/Views/Shared/_Layout.cshtmlSelect Use a layout page and enter ~/Views/Shared/_Layout.cshtml.
    • 选择 添加Select Add.
  3. 接下来,选择“添加”并让 Visual Studio 创建新的模板视图。Next select Add and let Visual Studio create a new template view. 将生成的文件中的代码替换为以下内容:Replace the code in the generated file with the following contents:

    @model todo.Models.Item
    
    @{
        ViewBag.Title = "Delete";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>Delete a To-Do Item</h2>
    
    <h3>Are you sure you want to delete this?</h3>
    <div>
        <hr />
        <dl class="dl-horizontal">
            <dt>
                @Html.DisplayNameFor(model => model.Name)
            </dt>
    
            <dd>
                @Html.DisplayFor(model => model.Name)
            </dd>
    
            <dt>
                @Html.DisplayNameFor(model => model.Description)
            </dt>
    
            <dd>
                @Html.DisplayFor(model => model.Description)
            </dd>
    
            <dt>
                @Html.DisplayNameFor(model => model.Completed)
            </dt>
    
            <dd>
                @Html.DisplayFor(model => model.Completed)
            </dd>
        </dl>
    
        @using (Html.BeginForm()) {
            @Html.AntiForgeryToken()
    
            <div class="form-actions no-color">
                <input type="submit" value="Delete" class="btn btn-default" /> |
                @Html.ActionLink("Back to List", "Index")
            </div>
        }
    </div>
    

添加用于获取项详细信息的视图Add a view to get an item details

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

  2. 在“添加 MVC 视图”中提供以下值:In Add MVC View, provide the following values:

    • 在“视图名称”中,输入“详细信息”。In View name, enter Details.
    • 在“模板”中选择“详细信息” 。In Template, select Details.
    • 在“模型类”中,选择“项(todo.Models)”。 In Model class, select Item (todo.Models).
    • 选择“使用布局页”并输入 ~/Views/Shared/_Layout.cshtmlSelect Use a layout page and enter ~/Views/Shared/_Layout.cshtml.
  3. 接下来,选择“添加”并让 Visual Studio 创建新的模板视图。Next select Add and let Visual Studio create a new template view. 将生成的文件中的代码替换为以下内容:Replace the code in the generated file with the following contents:

    @model todo.Models.Item
    
    <h2>View To-Do Item Details</h2>
    
    <div>
       <h4>Item</h4>
       <hr />
       <dl class="dl-horizontal">
           <dt>
               @Html.DisplayNameFor(model => model.Name)
           </dt>
    
           <dd>
               @Html.DisplayFor(model => model.Name)
           </dd>
    
           <dt>
               @Html.DisplayNameFor(model => model.Description)
           </dt>
    
           <dd>
               @Html.DisplayFor(model => model.Description)
           </dd>
    
           <dt>
               @Html.DisplayNameFor(model => model.Completed)
           </dt>
    
           <dd>
               @Html.DisplayFor(model => model.Completed)
           </dd>
    
       </dl>
    </div>
    <p>
       @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
       @Html.ActionLink("Back to List", "Index")
    </p>
    

添加“编辑项”视图Add an edit item view

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

  2. 在“添加 MVC 视图”中进行以下更改:In Add MVC View, make the following changes:

    • 在“视图名称”框中,键入“编辑”。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.cshtmlSelect Use a layout page and enter ~/Views/Shared/_Layout.cshtml.
    • 选择 添加Select Add.
  3. 接下来,选择“添加”并让 Visual Studio 创建新的模板视图。Next select Add and let Visual Studio create a new template view. 将生成的文件中的代码替换为以下内容:Replace the code in the generated file with the following contents:

    @model todo.Models.Item
    
    <h2>Edit a To-Do Item</h2>
    
    @using (Html.BeginForm())
    {
       @Html.AntiForgeryToken()
    
       <div class="form-horizontal">
           <h4>Item</h4>
           <hr />
           @Html.ValidationSummary(true, "", new { @class = "text-danger" })
           @Html.HiddenFor(model => model.Id)
    
           <div class="form-group">
               @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
               <div class="col-md-10">
                   @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                   @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
               </div>
           </div>
    
           <div class="form-group">
               @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
               <div class="col-md-10">
                   @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
                   @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
               </div>
           </div>
    
           <div class="form-group">
               @Html.LabelFor(model => model.Completed, htmlAttributes: new { @class = "control-label col-md-2" })
               <div class="col-md-10">
                   <div class="checkbox">
                       @Html.EditorFor(model => model.Completed)
                       @Html.ValidationMessageFor(model => model.Completed, "", new { @class = "text-danger" })
                   </div>
               </div>
           </div>
    
           <div class="form-group">
               <div class="col-md-offset-2 col-md-10">
                   <input type="submit" value="Save" class="btn btn-default" />
               </div>
           </div>
       </div>
    }
    
    <div>
       @Html.ActionLink("Back to List", "Index")
    </div>
    
    <script src="~/bundles/jqueryval"></script>
    

添加用于列出所有项的视图Add a view to list all the items

最后,通过以下步骤添加一个用于获取所有项的视图:And finally, add a view to get all the items with the following steps:

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

  2. 在“添加 MVC 视图”中进行以下更改:In Add MVC View, make the following changes:

    • 在“视图名称”框中,键入“索引”。******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.cshtmlSelect Use a layout page and enter ~/Views/Shared/_Layout.cshtml.
    • 选择 添加Select Add.
  3. 接下来,选择“添加”并让 Visual Studio 创建新的模板视图。Next select Add and let Visual Studio create a new template view. 将生成的文件中的代码替换为以下内容:Replace the code in the generated file with the following contents:

    @model IEnumerable<todo.Models.Item>
    
    @{
       ViewBag.Title = "List of To-Do Items";
       Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>List of To-Do Items</h2>
    
    <table class="table">
       <tr>
           <th>
               @Html.DisplayNameFor(model => model.Name)
           </th>
           <th>
               @Html.DisplayNameFor(model => model.Description)
           </th>
           <th>
               @Html.DisplayNameFor(model => model.Completed)
           </th>
           <th></th>
       </tr>
    
    @foreach (var item in Model) {
       <tr>
           <td>
               @Html.DisplayFor(modelItem => item.Name)
           </td>
           <td>
               @Html.DisplayFor(modelItem => item.Description)
           </td>
           <td>
               @Html.DisplayFor(modelItem => item.Completed)
           </td>
           <td>
               @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
               @Html.ActionLink("Details", "Details", new { id=item.Id }) |
               @Html.ActionLink("Delete", "Delete", new { id=item.Id })
           </td>
       </tr>
    }
    
    </table>
    
    <p>
       @Html.ActionLink("Create New", "Create")
    </p>
    

完成这些步骤后,请在 Visual Studio 中关闭所有 cshtml 文档。Once you complete these steps, close all the cshtml documents in Visual Studio.

声明并初始化服务Declare and initialize services

首先我们添加一个类,其中包含用于连接和使用 Azure Cosmos DB 的逻辑。First, we'll add a class that contains the logic to connect to and use Azure Cosmos DB. 在本教程中,我们会将该逻辑封装到名为 CosmosDBService 的类和名为 ICosmosDBService 的接口中。For this tutorial, we'll encapsulate this logic into a class called CosmosDBService and an interface called ICosmosDBService. 此服务执行 CRUD 操作。This service does the CRUD operations. 此外,它还执行读取源操作,例如列出不完整的项以及创建、编辑和删除项。It also does read feed operations such as listing incomplete items, creating, editing, and deleting the items.

  1. 在“解决方案资源管理器”中,右键单击项目并选择“添加” > “新建文件夹”。 In Solution Explorer, right-click your project and select Add > New Folder. 将文件夹命名为“服务”。Name the folder Services.

  2. 右键单击“服务”文件夹,并选择“添加” > “类”。 Right-click the Services folder, select Add > Class. 将新类命名为 CosmosDBService,然后选择“添加”。Name the new class CosmosDBService and select Add.

  3. CosmosDBService.cs 的内容替换为以下代码:Replace the contents of CosmosDBService.cs with the following code:

    namespace todo
    {
       using System.Collections.Generic;
       using System.Linq;
       using System.Threading.Tasks;
       using todo.Models;
       using Microsoft.Azure.Cosmos;
       using Microsoft.Azure.Cosmos.Fluent;
       using Microsoft.Extensions.Configuration;
    
       public class CosmosDbService : ICosmosDbService
       {
           private Container _container;
    
           public CosmosDbService(
               CosmosClient dbClient,
               string databaseName,
               string containerName)
           {
               this._container = dbClient.GetContainer(databaseName, containerName);
           }
    
           public async Task AddItemAsync(Item item)
           {
               await this._container.CreateItemAsync<Item>(item, new PartitionKey(item.Id));
           }
    
           public async Task DeleteItemAsync(string id)
           {
               await this._container.DeleteItemAsync<Item>(id, new PartitionKey(id));
           }
    
           public async Task<Item> GetItemAsync(string id)
           {
               try
               {
                   ItemResponse<Item> response = await this._container.ReadItemAsync<Item>(id, new PartitionKey(id));
                   return response.Resource;
               }
               catch(CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
               { 
                   return null;
               }
    
           }
    
           public async Task<IEnumerable<Item>> GetItemsAsync(string queryString)
           {
               var query = this._container.GetItemQueryIterator<Item>(new QueryDefinition(queryString));
               List<Item> results = new List<Item>();
               while (query.HasMoreResults)
               {
                   var response = await query.ReadNextAsync();
    
                   results.AddRange(response.ToList());
               }
    
               return results;
           }
    
           public async Task UpdateItemAsync(string id, Item item)
           {
               await this._container.UpsertItemAsync<Item>(item, new PartitionKey(id));
           }
       }
    }
    
  4. 右键单击“服务”文件夹,并选择“添加” > “类”。 Right-click the Services folder, select Add > Class. 将新类命名为“ICosmosDBService”,并选择“添加”。Name the new class ICosmosDBService and select Add.

  5. 将以下代码添加到 ICosmosDBService 类:Add the following code to ICosmosDBService class:

    namespace todo
    {
       using System.Collections.Generic;
       using System.Threading.Tasks;
       using todo.Models;
    
       public interface ICosmosDbService
       {
           Task<IEnumerable<Item>> GetItemsAsync(string query);
           Task<Item> GetItemAsync(string id);
           Task AddItemAsync(Item item);
           Task UpdateItemAsync(string id, Item item);
           Task DeleteItemAsync(string id);
       }
    }
    
  6. 在解决方案中打开 Startup.cs 文件,并添加方法 InitializeCosmosClientInstanceAsync,该方法将读取配置并初始化客户端。Open the Startup.cs file in your solution and add the following method InitializeCosmosClientInstanceAsync, which reads the configuration and initializes the client.

    /// <summary>
    /// Creates a Cosmos DB database and a container with the specified partition key. 
    /// </summary>
    /// <returns></returns>
    private static async Task<CosmosDbService> InitializeCosmosClientInstanceAsync(IConfigurationSection configurationSection)
    {
       string databaseName = configurationSection.GetSection("DatabaseName").Value;
       string containerName = configurationSection.GetSection("ContainerName").Value;
       string account = configurationSection.GetSection("Account").Value;
       string key = configurationSection.GetSection("Key").Value;
       Microsoft.Azure.Cosmos.CosmosClient client = new Microsoft.Azure.Cosmos.CosmosClient(account, key);
       CosmosDbService cosmosDbService = new CosmosDbService(client, databaseName, containerName);
       Microsoft.Azure.Cosmos.DatabaseResponse database = await client.CreateDatabaseIfNotExistsAsync(databaseName);
       await database.Database.CreateContainerIfNotExistsAsync(containerName, "/id");
    
       return cosmosDbService;
    }
    
    
  7. 在同一文件中,将 ConfigureServices 方法替换为:On that same file, replace the ConfigureServices method with:

    public void ConfigureServices(IServiceCollection services)
    {
       services.AddControllersWithViews();
       services.AddSingleton<ICosmosDbService>(InitializeCosmosClientInstanceAsync(Configuration.GetSection("CosmosDb")).GetAwaiter().GetResult());
    }
    
    

    此步骤中的代码会根据配置,将客户端初始化为要通过 ASP.NET Core 中的依赖项注入功能注入的单一实例。The code in this step initializes the client based on the configuration as a singleton instance to be injected through Dependency injection in ASP.NET Core.

    通过在同一文件的 Configure 方法中编辑路由,确保将默认 MVC 控制器更改为 ItemAnd make sure to change the default MVC Controller to Item by editing the routes in the Configure method of the same file:

    app.UseEndpoints(endpoints =>
          {
                endpoints.MapControllerRoute(
                   name: "default",
                   pattern: "{controller=Item}/{action=Index}/{id?}");
          });
    
  8. 在项目的 appsettings.json 文件中定义配置,如以下代码片段所示:Define the configuration in the project's appsettings.json file as shown in the following snippet:

    {
     "Logging": {
       "LogLevel": {
         "Default": "Warning"
       }
     },
     "AllowedHosts": "*",
     "CosmosDb": {
       "Account": "<Endpoint URI of your Azure Cosmos account>",
       "Key": "<PRIMARY KEY of your Azure Cosmos account>",
       "DatabaseName": "Tasks",
       "ContainerName": "Item"
     }
    }
    

添加控制器Add a controller

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

  2. 在“添加基架”中,依次选择“MVC 控制器 - 空”、“添加”。 In Add Scaffold, select MVC Controller - Empty and select Add.

    在“添加基架”中选择“MVC 控制器 - 空”

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

  4. ItemController.cs 的内容替换为以下代码:Replace the contents of ItemController.cs with the following code:

    namespace todo.Controllers
    {
       using System;
       using System.Threading.Tasks;
       using Microsoft.AspNetCore.Mvc;
       using todo.Models;
    
       public class ItemController : Controller
       {
           private readonly ICosmosDbService _cosmosDbService;
           public ItemController(ICosmosDbService cosmosDbService)
           {
               _cosmosDbService = cosmosDbService;
           }
    
           [ActionName("Index")]
           public async Task<IActionResult> Index()
           {
               return View(await _cosmosDbService.GetItemsAsync("SELECT * FROM c"));
           }
    
           [ActionName("Create")]
           public IActionResult Create()
           {
               return View();
           }
    
           [HttpPost]
           [ActionName("Create")]
           [ValidateAntiForgeryToken]
           public async Task<ActionResult> CreateAsync([Bind("Id,Name,Description,Completed")] Item item)
           {
               if (ModelState.IsValid)
               {
                   item.Id = Guid.NewGuid().ToString();
                   await _cosmosDbService.AddItemAsync(item);
                   return RedirectToAction("Index");
               }
    
               return View(item);
           }
    
           [HttpPost]
           [ActionName("Edit")]
           [ValidateAntiForgeryToken]
           public async Task<ActionResult> EditAsync([Bind("Id,Name,Description,Completed")] Item item)
           {
               if (ModelState.IsValid)
               {
                   await _cosmosDbService.UpdateItemAsync(item.Id, item);
                   return RedirectToAction("Index");
               }
    
               return View(item);
           }
    
           [ActionName("Edit")]
           public async Task<ActionResult> EditAsync(string id)
           {
               if (id == null)
               {
                   return BadRequest();
               }
    
               Item item = await _cosmosDbService.GetItemAsync(id);
               if (item == null)
               {
                   return NotFound();
               }
    
               return View(item);
           }
    
           [ActionName("Delete")]
           public async Task<ActionResult> DeleteAsync(string id)
           {
               if (id == null)
               {
                   return BadRequest();
               }
    
               Item item = await _cosmosDbService.GetItemAsync(id);
               if (item == null)
               {
                   return NotFound();
               }
    
               return View(item);
           }
    
           [HttpPost]
           [ActionName("Delete")]
           [ValidateAntiForgeryToken]
           public async Task<ActionResult> DeleteConfirmedAsync([Bind("Id")] string id)
           {
               await _cosmosDbService.DeleteItemAsync(id);
               return RedirectToAction("Index");
           }
    
           [ActionName("Details")]
           public async Task<ActionResult> DetailsAsync(string id)
           {
               return View(await _cosmosDbService.GetItemAsync(id));
           }
       }
    }
    

此处使用的 ValidateAntiForgeryToken 属性可帮助此应用程序防止跨站点请求伪造攻击。The ValidateAntiForgeryToken attribute is used here to help protect this application against cross-site request forgery attacks. 你的视图应该也可以使用此防伪令牌。Your views should work with this anti-forgery token as well. 有关详细信息和示例,请参阅在 ASP.NET MVC 应用程序中防止跨站点请求伪造 (CSRF) 攻击For more information and examples, see Preventing Cross-Site Request Forgery (CSRF) Attacks in ASP.NET MVC Application. GitHub 上提供的源代码已有完整实现。The source code provided on GitHub has the full implementation in place.

我们还会在方法参数中使用 Bind 属性,帮助防范过度提交攻击。We also use the Bind attribute on the method parameter to help protect against over-posting attacks. 有关详细信息,请参阅教程:使用 ASP.NET MVC 中的实体框架实现 CRUD 功能For more information, see Tutorial: Implement CRUD Functionality with the Entity Framework in ASP.NET MVC.

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

若要在本地计算机中测试应用程序,请使用以下步骤:To test the application on your local computer, use the following steps:

  1. 在 Visual Studio 中按 F5 即可在调试模式下构建应用程序。Press 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 应用程序的屏幕截图

    如果应用程序改为打开到主页,请将 /Item 追加到 url。If the application instead opens to the home page, append /Item to the url.

  2. 选择“新建”链接,并在“名称”和“说明”字段中添加值。 Select the Create New link and add values to the Name and Description fields. 将“已完成”复选框保留未选中状态。Leave the Completed check box unselected. 如果选中此复选框,应用会添加处于已完成状态的新项。If you select it, the app adds the new item in a completed state. 该项不再会显示在初始列表中。The item no longer appears on the initial list.

  3. 选择“创建” 。Select Create. 应用会将你返回到“索引”视图,项将显示在列表中。The app sends you back to the Index view, and your item appears in the list. 可以在 To-Do 列表中额外添加几个项。You can add a few more items to your To-Do list.

    “索引”视图的屏幕截图

  4. 在列表中“项”的旁边选择“编辑”。 Select Edit next to an Item on the list. 应用将会打开“编辑”视图,可在其中更新对象的任何属性,包括“已完成”标志。 The app opens the Edit view where you can update any property of your object, including the Completed flag. 如果你依次选择“已完成”、“保存”,则应用会在列表中显示处于已完成状态的“项”。 If you select Completed and select Save, the app displays the Item as completed in the list.

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

  5. 使用 Cosmos 资源管理器或 Azure Cosmos DB 仿真器的数据资源管理器来验证 Azure Cosmos DB 服务中数据的状态。Verify the state of the data in the Azure Cosmos DB service using Cosmos Explorer or the Azure Cosmos DB Emulator's Data Explorer.

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

步骤 6:部署应用程序Step 6: Deploy the application

现在,已经拥有了可以使用 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, right-click the project in Solution Explorer and select Publish.

  2. 在“选取发布目标”中选择“应用服务”。 In Pick a publish target, select App Service.

  3. 若要使用现有的应用服务配置文件,请依次选择“选择现有项”、“发布”。 To use an existing App Service profile, choose Select Existing, then select Publish.

  4. 在“应用服务”中选择“订阅”。 In App Service, select a Subscription. 使用“视图”筛选器按资源组或资源类型进行筛选。Use the View filter to sort by resource group or resource type.

  5. 找到你的配置文件,然后选择“确定”。Find your profile, and then select OK. 接下来搜索必需的 Azure 应用服务,然后选择“确定”。Next search the required Azure App Service and select OK.

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

另一个选项是创建新的配置文件:Another option is to create a new profile:

  1. 与在前面的过程中一样,在“解决方案资源管理器”右键单击该项目并选择“发布”。 As in the previous procedure, right-click the project in Solution Explorer and select Publish.

  2. 在“选取发布目标”中选择“应用服务”。 In Pick a publish target, select App Service.

  3. 在“选取发布目标”中,依次选择“新建”、“发布”。 In Pick a publish target, select Create New and select Publish.

  4. 在“应用服务”中,输入 Web 应用名称以及相应的订阅、资源组和托管计划,然后选择“创建”。 In App Service, enter your Web App name and the appropriate subscription, resource group, and hosting plan, then select Create.

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

在几秒钟内,Visual Studio 会发布 Web 应用程序并启动浏览器,方便你查看在 Azure 中运行的项目!In a few seconds, Visual Studio publishes your web application and launches a browser where you can see your project running in Azure!

后续步骤Next steps

本教程介绍了如何生成 ASP.NET Core MVC Web 应用程序。In this tutorial, you've learned how to build an ASP.NET Core MVC web application. 该应用程序可以访问存储在 Azure Cosmos DB 中的数据。Your application can access data stored in Azure Cosmos DB. 接下来,可以继续学习以下资源:You can now continue with these resources: