教程:在 Azure 应用服务中生成 ASP.NET Core 和 SQL 数据库应用Tutorial: Build an ASP.NET Core and SQL Database app in Azure App Service

应用服务在 Azure 中提供高度可缩放、自修补的 Web 托管服务。App Service provides a highly scalable, self-patching web hosting service in Azure. 本教程演示如何创建 .NET Core 应用,并将其连接至 SQL 数据库。This tutorial shows how to create a .NET Core app and connect it to a SQL Database. 完成操作后,将拥有一个在应用服务中运行的 .NET Core MVC 应用。When you're done, you'll have a .NET Core MVC app running in App Service.

在应用服务中运行的应用

你将学习如何:What you learn how to:

  • 在 Azure 中创建 SQL 数据库。Create a SQL Database in Azure
  • 将 .NET Core 应用连接到 SQL 数据库Connect a .NET Core app to SQL Database
  • 将应用部署到 AzureDeploy the app to Azure
  • 更新数据模型并重新部署应用Update the data model and redeploy the app
  • 从 Azure 流式传输诊断日志Stream diagnostic logs from Azure
  • 在 Azure 门户中管理应用Manage the app in the Azure portal

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

先决条件Prerequisites

完成本教程:To complete this tutorial:

创建本地 .NET Core 应用Create local .NET Core app

在此步骤中,你将设置本地 .NET Core 项目。In this step, you set up the local .NET Core project.

克隆示例应用程序Clone the sample application

在终端窗口中,通过 cd 转到工作目录。In the terminal window, cd to a working directory.

运行以下命令来克隆示例存储库,并更改为其根。Run the following commands to clone the sample repository and change to its root.

git clone https://github.com/azure-samples/dotnetcore-sqldb-tutorial
cd dotnetcore-sqldb-tutorial

此示例项目包含使用Entity Framework Core的基本 CRUD(创建-读取-更新-删除)应用。The sample project contains a basic CRUD (create-read-update-delete) app using Entity Framework Core.

运行应用程序Run the application

运行以下命令,安装所需的包,运行数据库迁移并启动应用程序。Run the following commands to install the required packages, run database migrations, and start the application.

dotnet restore
dotnet ef database update
dotnet run

在浏览器中导航至 http://localhost:5000Navigate to http://localhost:5000 in a browser. 选择“新建” 链接,创建几个待办事项 。Select the Create New link and create a couple to-do items.

已成功连接到 SQL 数据库

在终端按 Ctrl+C,随时停止 .NET Core。To stop .NET Core at any time, press Ctrl+C in the terminal.

创建生产环境 SQL 数据库Create production SQL Database

此步骤在 Azure 中创建一个 SQL 数据库。In this step, you create a SQL Database in Azure. 应用部署到 Azure 后,它将使用该云数据库。When your app is deployed to Azure, it uses this cloud database.

对于 SQL 数据库,本教程使用 Azure SQL 数据库For SQL Database, this tutorial uses Azure SQL Database.

创建资源组Create a resource group

资源组是在其中部署和管理 Azure 资源(例如 Web 应用、数据库和存储帐户)的逻辑容器。A resource group is a logical container into which Azure resources like web apps, databases, and storage accounts are deployed and managed.

在 Azure CLI 中,使用 az group create 命令创建资源组。In the Azure CLI, create a resource group with the az group create command. 以下示例在“中国北部” 位置创建名为“myResourceGroup” 的资源组。The following example creates a resource group named myResourceGroup in the China North location. 要查看“免费”层中应用服务支持的所有位置,请运行 az appservice list-locations --sku FREE 命令。 To see all supported locations for App Service in Free tier, run the az appservice list-locations --sku FREE command.

az group create --name myResourceGroup --location "China North"

通常在附近的区域中创建资源组和资源。You generally create your resource group and the resources in a region near you.

此命令完成后,JSON 输出会显示资源组属性。When the command finishes, a JSON output shows you the resource group properties.

创建 SQL 数据库逻辑服务器Create a SQL Database logical server

在 Azure CLI 中,使用 az sql server create 命令创建 SQL 数据库逻辑服务器。In Azure CLI, create a SQL Database logical server with the az sql server create command.

将 <server_name> 占位符替换为唯一的 SQL 数据库名称 。Replace the <server_name> placeholder with a unique SQL Database name. 此名称用作 SQL 数据库终结点 <server_name>.database.chinacloudapi.cn 的一部分,因此必须在 Azure 的所有逻辑服务器中具有唯一性。This name is used as the part of the SQL Database endpoint, <server_name>.database.chinacloudapi.cn, so the name needs to be unique across all logical servers in Azure. 它只能包含小写字母、数字及连字符(-),长度必须为 3 到 50 个字符。The name must contain only lowercase letters, numbers, and the hyphen (-) character, and must be between 3 and 50 characters long. 此外,将 <db_username> 和 <db_password> 分别替换为所选用户名和密码 。Also, replace <db_username> and <db_password> with a username and password of your choice.

az sql server create --name <server_name> --resource-group myResourceGroup --location "China East" --admin-user <db_username> --admin-password <db_password>

创建 SQL 数据库逻辑服务器后,Azure CLI 会显示类似于以下示例的信息:When the SQL Database logical server is created, the Azure CLI shows information similar to the following example:

{
  "administratorLogin": "sqladmin",
  "administratorLoginPassword": null,
  "fullyQualifiedDomainName": "<server_name>.database.chinacloudapi.cn",
  "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Sql/servers/<server_name>",
  "identity": null,
  "kind": "v12.0",
  "location": "chinaeast",
  "name": "<server_name>",
  "resourceGroup": "myResourceGroup",
  "state": "Ready",
  "tags": null,
  "type": "Microsoft.Sql/servers",
  "version": "12.0"
}

配置服务器防火墙规则Configure a server firewall rule

使用 az sql server firewall create 命令创建 Azure SQL 数据库服务器级防火墙规则Create an Azure SQL Database server-level firewall rule using the az sql server firewall create command. 若同时将起始 IP 和结束 IP 设置为 0.0.0.0,防火墙将仅对其他 Azure 资源开启。When both starting IP and end IP are set to 0.0.0.0, the firewall is only opened for other Azure resources.

az sql server firewall-rule create --resource-group myResourceGroup --server <server_name> --name AllowAllIps --start-ip-address 0.0.0.0 --end-ip-address 0.0.0.0

Tip

你甚至可以让防火墙规则更严格,即只使用应用所使用的出站 IP 地址You can be even more restrictive in your firewall rule by using only the outbound IP addresses your app uses.

创建数据库Create a database

使用 az sql db create 命令在服务器中创建 S0 性能级别的数据库。Create a database with an S0 performance level in the server using the az sql db create command.

az sql db create --resource-group myResourceGroup --server <server_name> --name coreDB --service-objective S0

创建连接字符串Create connection string

将下列字符串替换为先前所使用的 <server_name>、<db_username> 和 <db_password> 。Replace the following string with the <server_name>, <db_username>, and <db_password> you used earlier.

Server=tcp:<server_name>.database.chinacloudapi.cn,1433;Database=coreDB;User ID=<db_username>;Password=<db_password>;Encrypt=true;Connection Timeout=30;

这是 .NET Core 应用的连接字符串。This is the connection string for your .NET Core app. 将其进行复制,留待稍后使用。Copy it for use later.

将应用部署到 AzureDeploy app to Azure

在此步骤中,将已连接 SQL 数据库的 .NET Core 应用程序部署到应用服务。In this step, you deploy your SQL Database-connected .NET Core application to App Service.

配置本地 Git 部署Configure local git deployment

可以使用“部署用户” 将 FTP 和本地 Git 部署到 Azure Web 应用。FTP and local Git can deploy to an Azure web app by using a deployment user. 配置部署用户之后,可对所有 Azure 部署使用此用户。Once you configure your deployment user, you can use it for all your Azure deployments. 帐户级部署用户名和密码不同于 Azure 订阅凭据。Your account-level deployment username and password are different from your Azure subscription credentials.

若要配置部署用户,请在 Azure Cloud Shell 中运行 az webapp deployment user set 命令。To configure the deployment user, run the az webapp deployment user set command in Azure Cloud Shell. 将 <username> 和 <password> 替换为部署用户名和密码。Replace <username> and <password> with a deployment user username and password.

  • 用户名必须在 Azure 中唯一,并且对于本地 Git 推送,不能包含“@”符号。The username must be unique within Azure, and for local Git pushes, must not contain the �@� symbol.
  • 密码必须至少为 8 个字符,且具有字母、数字和符号这三种元素中的两种。The password must be at least eight characters long, with two of the following three elements: letters, numbers, and symbols.
az webapp deployment user set --user-name <username> --password <password>

JSON 输出会将该密码显示为 nullThe JSON output shows the password as null. 如果收到 'Conflict'. Details: 409 错误,请更改用户名。If you get a 'Conflict'. Details: 409 error, change the username. 如果收到 'Bad Request'. Details: 400 错误,请使用更强的密码。If you get a 'Bad Request'. Details: 400 error, use a stronger password.

请记录你要用于部署 Web 应用的用户名和密码。Record your username and password to use to deploy your web apps.

创建应用服务计划Create an App Service plan

使用 az appservice plan create 命令创建应用服务计划。Create an App Service plan with the az appservice plan create command.

应用服务计划指定托管应用的 Web 服务器场的位置、大小和功能。An App Service plan specifies the location, size, and features of the web server farm that hosts your app. 可以在托管多个应用时节省资金,方法是将多个 Web 应用配置为共用单个应用服务计划。You can save money when hosting multiple apps by configuring the web apps to share a single App Service plan.

应用服务计划定义:App Service plans define:

  • 区域(例如:中国东部、中国东部 2、中国北部、中国北部 2)Region (for example: China East, China East 2, China North, China North 2)
  • 实例大小(小、中、大)Instance size (small, medium, or large)
  • 规模计数(1 到 20 个实例)Scale count (1 to 20 instances)
  • SKU(免费、共享、基本、标准、高级)SKU (Free, Shared, Basic, Standard, or Premium)

以下示例在免费 定价层中创建名为 myAppServicePlan 的应用服务计划:The following example creates an App Service plan named myAppServicePlan in the Free pricing tier:

az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku FREE

创建应用服务计划后,Azure CLI 将显示类似于以下示例的信息:When the App Service plan has been created, the Azure CLI shows information similar to the following example:

{ 
  "adminSiteName": null,
  "appServicePlanName": "myAppServicePlan",
  "geoRegion": "China North",
  "hostingEnvironmentProfile": null,
  "id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
  "kind": "app",
  "location": "China North",
  "maximumNumberOfWorkers": 1,
  "name": "myAppServicePlan",
  < JSON data removed for brevity. >
  "targetWorkerSizeId": 0,
  "type": "Microsoft.Web/serverfarms",
  "workerTierName": null
} 

创建 Web 应用Create a web app

myAppServicePlan 应用服务计划中创建一个 Web 应用。Create a web app in the myAppServicePlan App Service plan.

在 Azure CLI 中,可以使用 az webapp create 命令。In the Azure CLI, you can use the az webapp create command. 在以下示例中,将 <app-name> 替换为全局唯一的应用名称(有效字符是 a-z0-9-)。In the following example, replace <app-name> with a globally unique app name (valid characters are a-z, 0-9, and -).

az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app_name> --deployment-local-git

创建 Web 应用后,Azure CLI 会显示类似于以下示例的输出:When the web app has been created, the Azure CLI shows output similar to the following example:

Local git is configured with url of 'https://<username>@<app-name>.scm.chinacloudsites.cn/<app-name>.git'
{
  "availabilityState": "Normal",
  "clientAffinityEnabled": true,
  "clientCertEnabled": false,
  "cloningInfo": null,
  "containerSize": 0,
  "dailyMemoryTimeQuota": 0,
  "defaultHostName": "<app-name>.chinacloudsites.cn",
  "deploymentLocalGitUrl": "https://<username>@<app-name>.scm.chinacloudsites.cn/<app-name>.git",
  "enabled": true,
  < JSON data removed for brevity. >
}

Note

Git 远程的 URL 将显示在 deploymentLocalGitUrl 属性中,其格式为 https://<username>@<app_name>.scm.chinacloudsites.cn/<app-name>.gitThe URL of the Git remote is shown in the deploymentLocalGitUrl property, with the format https://<username>@<app_name>.scm.chinacloudsites.cn/<app-name>.git. 保存此 URL,因为后面需要它。Save this URL as you need it later.

配置连接字符串Configure connection string

若要为 Azure 应用设置连接字符串,请在 Azure CLI 中使用 az webapp config appsettings set 命令。To set connection strings for your Azure app, use the az webapp config appsettings set command in Azure CLI. 在下列命令中,将 <app name> 和 <connection_string> 参数替换为先前创建的连接字符串 。In the following command, replace <app name>, as well as the <connection_string> parameter with the connection string you created earlier.

az webapp config connection-string set --resource-group myResourceGroup --name <app name> --settings MyDbConnection='<connection_string>' --connection-string-type SQLServer

在 ASP.NET Core 中,可以通过标准模式使用此命名连接字符串 (MyDbConnection),就像在 appsettings.json 中指定的任何连接字符串一样。In ASP.NET Core, you can use this named connection string (MyDbConnection) using the standard pattern, like any connection string specified in appsettings.json. 在本例中,MyDbConnection 也在 appsettings.json 中定义。In this case, MyDbConnection is also defined in your appsettings.json. 在应用服务中运行时,应用服务中定义的连接字符串优先于 appsettings.json 中定义的连接字符串。When running in App Service, the connection string defined in App Service takes precedence over the connection string defined in your appsettings.json. 此代码在本地开发过程中使用 appsettings.json 值,相同的代码在部署时使用应用服务值。The code uses the appsettings.json value during local development, and the same code uses the App Service value when deployed.

若要了解如何在代码中引用连接字符串,请参阅在生产环境中连接到 SQL 数据库To see how the connection string is referenced in your code, see Connect to SQL Database in production.

配置环境变量Configure environment variable

接下来,将 ASPNETCORE_ENVIRONMENT 应用设置设置为_生产_。Next, set ASPNETCORE_ENVIRONMENT app setting to Production. 由于对本地开发环境使用 SQLite,并对 Azure 环境使用 SQL 数据库,因此通过此设置,你可以了解应用是否正在 Azure 中运行。This setting lets you know whether you're running in Azure, because you use SQLite for your local development environment and SQL Database for your Azure environment.

以下示例在 Azure 应用中配置 ASPNETCORE_ENVIRONMENT 应用设置。The following example configures a ASPNETCORE_ENVIRONMENT app setting in your Azure app. 替换 <app_name> 占位符 。Replace the <app_name> placeholder.

az webapp config appsettings set --name <app_name> --resource-group myResourceGroup --settings ASPNETCORE_ENVIRONMENT="Production"

若要了解如何在代码中引用环境变量,请参阅在生产环境中连接到 SQL 数据库To see how the environment variable is referenced in your code, see Connect to SQL Database in production.

在生产环境中连接到 SQL 数据库Connect to SQL Database in production

在本地存储库中,打开 Startup.cs 并查找下列代码:In your local repository, open Startup.cs and find the following code:

services.AddDbContext<MyDatabaseContext>(options =>
        options.UseSqlite("Data Source=localdatabase.db"));

将其替换为下列代码,该代码使用之前配置的环境变量。Replace it with the following code, which uses the environment variables that you configured earlier.

// Use SQL Database if in Azure, otherwise, use SQLite
if(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production")
    services.AddDbContext<MyDatabaseContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("MyDbConnection")));
else
    services.AddDbContext<MyDatabaseContext>(options =>
            options.UseSqlite("Data Source=localdatabase.db"));

// Automatically perform database migration
services.BuildServiceProvider().GetService<MyDatabaseContext>().Database.Migrate();

如果此代码检测到当前正在生产环境中运行(指 Azure 环境),则会使用已配置的连接字符串连接到 SQL 数据库。If this code detects that it's running in production (which indicates the Azure environment), then it uses the connection string you configured to connect to the SQL Database.

在 Azure 中运行时可利用 Database.Migrate() 调用,因为它会根据迁移配置自动创建 .NET Core 应用所需的数据库。The Database.Migrate() call helps you when it's run in Azure, because it automatically creates the databases that your .NET Core app needs, based on its migration configuration.

Important

对于需要横向扩展的生产应用,请遵循在生产中应用迁移中的最佳做法。For production apps that need to scale out, follow the best practices in Applying migrations in production.

保存所做的更改,然后将其提交到 Git 存储库。Save your changes, then commit it into your Git repository.

git add .
git commit -m "connect to SQLDB in Azure"

从 Git 推送到 AzurePush to Azure from Git

回到本地终端窗口 ,将 Azure 远程功能添加到本地 Git 存储库。Back in the local terminal window, add an Azure remote to your local Git repository. <deploymentLocalGitUrl-from-create-step> 替换为在创建 Web 应用中保存的 Git 远程 URL。Replace <deploymentLocalGitUrl-from-create-step> with the URL of the Git remote that you saved from Create a web app.

git remote add azure <deploymentLocalGitUrl-from-create-step>

使用以下命令推送到 Azure 远程功能以部署应用。Push to the Azure remote to deploy your app with the following command. 当 Git 凭据管理器提示输入凭据时,请确保输入在配置部署用户中创建的凭据,而不是用于登录到 Azure 门户的凭据。When prompted for credentials by Git Credential Manager, make sure that you enter the credentials you created in Configure a deployment user, not the credentials you use to sign in to the Azure portal.

git push azure master

此命令可能需要花费几分钟时间运行。This command may take a few minutes to run. 运行时,该命令会显示类似于以下示例的信息:While running, it displays information similar to the following example:

Counting objects: 98, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (92/92), done.
Writing objects: 100% (98/98), 524.98 KiB | 5.58 MiB/s, done.
Total 98 (delta 8), reused 0 (delta 0)
remote: Updating branch 'master'.
remote: .
remote: Updating submodules.
remote: Preparing deployment for commit id '0c497633b8'.
remote: Generating deployment script.
remote: Project file path: ./DotNetCoreSqlDb.csproj
remote: Generated deployment script files
remote: Running deployment command...
remote: Handling ASP.NET Core Web Application deployment.
remote: .
remote: .
remote: .
remote: Finished successfully.
remote: Running post deployment command(s)...
remote: Deployment successful.
remote: App container will begin restart within 10 seconds.
To https://<app_name>.scm.chinacloudsite.cn/<app_name>.git
 * [new branch]      master -> master

浏览到 Azure 应用Browse to the Azure app

使用 Web 浏览器浏览到已部署的应用。Browse to the deployed app using your web browser.

http://<app_name>.chinacloudsite.cn

添加多个待办事项。Add a few to-do items.

在应用服务中运行的应用

祝贺你!Congratulations! 数据驱动的 .NET Core 应用已经在你的应用服务中运行了。You're running a data-driven .NET Core app in App Service.

在本地更新并重新部署Update locally and redeploy

在此步骤中,将对数据库架构做出更改,并将其发布至 Azure。In this step, you make a change to your database schema and publish it to Azure.

更新数据模型Update your data model

在代码编辑器中打开 Models\Todo.csOpen Models\Todo.cs in the code editor. 将以下属性添加到 ToDo 类:Add the following property to the ToDo class:

public bool Done { get; set; }

本地运行 Code First 迁移Run Code First Migrations locally

运行以下命令更新本地数据库。Run a few commands to make updates to your local database.

dotnet ef migrations add AddProperty

更新本地数据库:Update the local database:

dotnet ef database update

使用新属性Use the new property

为了使用 Done 属性,请对代码做一些更改。Make some changes in your code to use the Done property. 简单起见,本教程中将仅更改 IndexCreate 视图,以便在操作中查看属性。For simplicity in this tutorial, you're only going to change the Index and Create views to see the property in action.

打开 Controllers\TodosController.csOpen Controllers\TodosController.cs.

找到 Create([Bind("ID,Description,CreatedDate")] Todo todo) 方法,并将 Done 添加到 Bind 属性中的属性列表。Find the Create([Bind("ID,Description,CreatedDate")] Todo todo) method and add Done to the list of properties in the Bind attribute. 完成后,Create() 方法签名如以下代码所示:When you're done, your Create() method signature looks like the following code:

public async Task<IActionResult> Create([Bind("ID,Description,CreatedDate,Done")] Todo todo)

打开 Views\Todos\Create.cshtmlOpen Views\Todos\Create.cshtml.

在 Razor 代码中,应能看到用于 Description<div class="form-group"> 元素,以及另一个用于 CreatedDate<div class="form-group"> 元素。In the Razor code, you should see a <div class="form-group"> element for Description, and then another <div class="form-group"> element for CreatedDate. 紧跟在这两个元素之后,添加另一个用于 Done<div class="form-group"> 元素:Immediately following these two elements, add another <div class="form-group"> element for Done:

<div class="form-group">
    <label asp-for="Done" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <input asp-for="Done" class="form-control" />
        <span asp-validation-for="Done" class="text-danger"></span>
    </div>
</div>

打开 Views\Todos\Index.cshtmlOpen Views\Todos\Index.cshtml.

搜索空的 <th></th> 元素。Search for the empty <th></th> element. 在此元素的正上方,添加下列 Razor 代码:Just above this element, add the following Razor code:

<th>
    @Html.DisplayNameFor(model => model.Done)
</th>

查找包含 asp-action 标记帮助程序的 <td> 元素。Find the <td> element that contains the asp-action tag helpers. 在此元素的正上方,添加下列 Razor 代码:Just above this element, add the following Razor code:

<td>
    @Html.DisplayFor(modelItem => item.Done)
</td>

这就是要在 IndexCreate 视图中查看更改所需的全部操作。That's all you need to see the changes in the Index and Create views.

在本地测试更改Test your changes locally

在本地运行应用。Run the app locally.

dotnet run

在浏览器中,导航到 http://localhost:5000/In your browser, navigate to http://localhost:5000/. 你现在可以添加一个待办事项,并检查DoneYou can now add a to-do item and check Done. 然后,它应作为已完成项在主页中显示。Then it should show up in your homepage as a completed item. 请牢记,由于未更改Edit视图,Edit视图不显示Done字段。Remember that the Edit view doesn't show the Done field, because you didn't change the Edit view.

发布对 Azure 所做的更改Publish changes to Azure

git add .
git commit -m "added done field"
git push azure master

git push 完成后,请导航至应用服务应用,尝试添加一个待办事项并选中“完成” 。Once the git push is complete, navigate to your App Service app and try adding a to-do item and check Done.

Code First 迁移后的 Azure 应用

所有现有待办事项仍将显示。All your existing to-do items are still displayed. 重新发布 .NET Core 应用时,SQL 数据库中的现有数据不会丢失。When you republish your .NET Core app, existing data in your SQL Database isn't lost. 此外,实体框架核心迁移仅更改数据架构,而使现有数据保持不变。Also, Entity Framework Core Migrations only changes the data schema and leaves your existing data intact.

流式传输诊断日志Stream diagnostic logs

当 ASP.NET Core 应用在 Azure 应用服务中运行时,可以将控制台日志通过管道传输到 Azure CLI。While the ASP.NET Core app runs in Azure App Service, you can get the console logs piped to Azure CLI. 这样可以获得相同的诊断消息,以帮助调试应用程序错误。That way, you can get the same diagnostic messages to help you debug application errors.

示例项目已遵循了 Azure 中的 ASP.NET Core 日志记录中的指南,并且进行了两个配置更改:The sample project already follows the guidance at ASP.NET Core Logging in Azure with two configuration changes:

  • DotNetCoreSqlDb.csproj 中包括了对 Microsoft.Extensions.Logging.AzureAppServices 的引用。Includes a reference to Microsoft.Extensions.Logging.AzureAppServices in DotNetCoreSqlDb.csproj.
  • Program.cs 中调用 loggerFactory.AddAzureWebAppDiagnostics()Calls loggerFactory.AddAzureWebAppDiagnostics() in Program.cs.

若要将应用服务中的 ASP.NET Core 日志级别从默认级别 Error 设置为 Information,请在 Cloud Shell 中使用 az webapp log config 命令。To set the ASP.NET Core log level in App Service to Information from the default level Error, use the az webapp log config command in the Cloud Shell.

az webapp log config --name <app_name> --resource-group myResourceGroup --application-logging true --level information

Note

项目的日志级别在 appsettings.json 中已设置为 InformationThe project's log level is already set to Information in appsettings.json.

若要启动日志流式处理,请在 Azure CLI 中使用 az webapp log tail 命令。To start log streaming, use the az webapp log tail command in Azure CLI.

az webapp log tail --name <app_name> --resource-group myResourceGroup

启动日志流式处理后,请在浏览器中刷新 Azure 应用,以获取一些 Web 流量。Once log streaming has started, refresh the Azure app in the browser to get some web traffic. 现在可以看到通过管道传送到终端的控制台日志。You can now see console logs piped to the terminal. 如果没有立即看到控制台日志,请在 30 秒后重新查看。If you don't see console logs immediately, check again in 30 seconds.

若要随时停止日志流式处理,请键入 Ctrl+CTo stop log streaming at any time, type Ctrl+C.

有关自定义 ASP.NET Core 日志的详细信息,请参阅 ASP.NET Core 中的日志记录For more information on customizing the ASP.NET Core logs, see Logging in ASP.NET Core.

管理 Azure 应用Manage your Azure app

转到 Azure 门户查看创建的应用。Go to the Azure portal to see the app you created.

在左侧菜单中单击“应用服务”,然后单击 Azure 应用的名称。 From the left menu, click App Services, then click the name of your Azure app.

在门户中导航到 Azure 应用

默认情况下,门户将显示应用的 “概述”页。By default, the portal shows your app's Overview page. 在此页中可以查看应用的运行状况。This page gives you a view of how your app is doing. 在此处还可以执行基本的管理任务,例如浏览、停止、启动、重新启动和删除。Here, you can also perform basic management tasks like browse, stop, start, restart, and delete. 页面左侧的选项卡显示可以打开的不同配置页。The tabs on the left side of the page show the different configuration pages you can open.

Azure 门户中的“应用服务”页

清理资源Clean up resources

若要清理资源,请运行以下命令:To clean up your resources, run the following command:

az group delete --name myResourceGroup

后续步骤Next steps

你已了解:What you learned:

  • 在 Azure 中创建 SQL 数据库。Create a SQL Database in Azure
  • 将 .NET Core 应用连接到 SQL 数据库Connect a .NET Core app to SQL Database
  • 将应用部署到 AzureDeploy the app to Azure
  • 更新数据模型并重新部署应用Update the data model and redeploy the app
  • 将日志从 Azure 流式传输到终端Stream logs from Azure to your terminal
  • 在 Azure 门户中管理应用Manage the app in the Azure portal

继续学习下一篇教程,了解如何将自定义 DNS 名称映射到应用。Advance to the next tutorial to learn how to map a custom DNS name to your app.