快速入门:在 Azure 中创建 ASP.NET Core Web 应用Quickstart: Create an ASP.NET Core web app in Azure

本快速入门介绍如何创建第一个 ASP.NET Core Web 应用并将其部署到 Azure 应用服务In this quickstart, you'll learn how to create and deploy your first ASP.NET Core web app to Azure App Service.

完成后,你将获得一个 Azure 资源组,其中包含一个应用服务托管计划,以及一个部署了 Web 应用程序的应用服务。When you're finished, you'll have an Azure resource group consisting of an App Service hosting plan and an App Service with a deployed web application.

先决条件Prerequisites

  • 具有活动订阅的 Azure 帐户。An Azure account with an active subscription. 创建试用帐户Create an account for trial.

  • 本快速入门将应用部署到 Windows 上的应用服务。This quickstart deploys an app to App Service on Windows. 若要部署 Linux 上的应用服务,请参阅在应用服务中创建 .NET Core Web 应用To deploy to App Service on Linux, see Create a .NET Core web app in App Service.

  • 安装带有 ASP.NET 和 Web 开发工作负荷的 Visual Studio 2019Install Visual Studio 2019 with the ASP.NET and web development workload.

    如果已安装 Visual Studio 2019:If you've installed Visual Studio 2019 already:

    • 通过选择“帮助” > “检查更新”,在 Visual Studio 中安装最新更新。Install the latest updates in Visual Studio by selecting Help > Check for Updates.
    • 通过选择“工具” > “获取工具和功能”,添加工作负荷。Add the workload by selecting Tools > Get Tools and Features.

创建一个 ASP.NET Core Web 应用Create an ASP.NET Core web app

遵循以下步骤在 Visual Studio 中创建 ASP.NET Core Web 应用:Create an ASP.NET Core web app in Visual Studio by following these steps:

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

  2. 在“创建新项目”中选择“ASP.NET Core Web 应用程序”,确认“C#”列在所选内容的语言中,然后选择“下一步”。In Create a new project, select ASP.NET Core Web Application and confirm that C# is listed in the languages for that choice, then select Next.

  3. 在“配置新项目”中,将 Web 应用程序项目命名为 myFirstAzureWebApp,然后选择“创建”。In Configure your new project, name your web application project myFirstAzureWebApp, and select Create.

    配置 Web 应用项目

  4. 可将任何类型的 ASP.NET Core Web 应用部署到 Azure,但对于本快速入门,请选择“Web 应用程序”模板。You can deploy any type of ASP.NET Core web app to Azure, but for this quickstart, choose the Web Application template. 确保“身份验证”设置为“无身份验证”,并且未选择其他选项。Make sure Authentication is set to No Authentication, and that no other option is selected. 然后选择“创建”。Then, select Create.

    创建新的 ASP.NET Core Web 应用

  5. 在 Visual Studio 菜单中,选择“调试” > “开始执行(不调试)”以在本地运行 Web 应用。From the Visual Studio menu, select Debug > Start Without Debugging to run your web app locally.

    Web 应用在本地运行

发布 Web 应用Publish your web app

若要发布 Web 应用,必须先创建并配置一个可将应用发布到的新应用服务。To publish your web app, you must first create and configure a new App Service that you can publish your app to.

在设置应用服务的过程中,将会创建:As part of setting up the App Service, you'll create:

  • 一个新的资源组,用于包含该服务的所有 Azure 资源。A new resource group to contain all of the Azure resources for the service.
  • 一个新的托管计划,用于指定托管应用的 Web 服务器场的位置、大小和功能。A new Hosting Plan that specifies the location, size, and features of the web server farm that hosts your app.

遵循以下步骤创建应用服务并发布 Web 应用:Follow these steps to create your App Service and publish your web app:

  1. 在“解决方案资源管理器”中右键单击“myFirstAzureWebApp”项目,然后选择“发布”。In Solution Explorer, right-click the myFirstAzureWebApp project and select Publish. 如果你尚未从 Visual Studio 登录到 Azure 帐户,请选择“添加帐户”或“登录”。If you haven't already signed-in to your Azure account from Visual Studio, select either Add an account or Sign in. 也可以创建免费 Azure 帐户。You can also create a free Azure account.

  2. 在“选择发布目标”对话框中,依次选择“应用服务”、“新建”、“创建配置文件”。In the Pick a publish target dialog box, choose App Service, select Create New, and then select Create Profile.

    选取发布目标

  3. 在“应用服务:新建”对话框中为应用提供全局唯一的名称,可以接受默认名称,也可以输入新名称。In the App Service: Create new dialog, provide a globally unique Name for your app by either accepting the default name, or entering a new name. 有效字符为:a-zA-Z0-9-Valid characters are: a-z, A-Z, 0-9, and -. 名称用作 Web 应用的 URL 前缀,采用 http://<app_name>.chinacloudsites.cn 格式。This Name is used as the URL prefix for your web app in the format http://<app_name>.chinacloudsites.cn.

  4. 对于“订阅”,请接受列出的订阅,或从下拉列表中选择一个新订阅。For Subscription, accept the subscription that is listed or select a new one from the drop-down list.

  5. 在“资源组”中选择“新建”。In Resource group, select New. 在“新资源组名称”中,输入“myResourceGroup”并选择“确定”。In New resource group name, enter myResourceGroup and select OK.

  6. 对于“托管计划”,请选择“新建”。For Hosting Plan, select New.

  7. 在“托管计划:新建”对话框中,输入下表中指定的值:In the Hosting Plan: Create new dialog, enter the values specified in the following table:

    设置Setting 建议的值Suggested Value 说明Description
    托管计划Hosting Plan myFirstAzureWebAppPlanmyFirstAzureWebAppPlan 应用服务计划的名称。Name of the App Service plan.
    位置Location 中国东部China East 托管 Web 应用的数据中心。The datacenter where the web app is hosted.
    大小Size 免费Free 定价层确定托管功能。Pricing tier determines hosting features.

    创建新的托管计划

  8. 将“Application Insights”保留设置为“无”。Leave Application Insights set to None.

  9. 在“应用服务:新建”对话框中,选择“创建”开始创建 Azure 资源。In the App Service: Create new dialog box, select Create to start creating the Azure resources.

    创建新的应用服务

  10. 完成向导中的操作后,选择“发布”。Once the wizard completes, select Publish.

    将 Web 应用发布到 Azure

    Visual Studio 会将 ASP.NET Core Web 应用发布到 Azure,并在默认浏览器中启动该应用。Visual Studio publishes your ASP.NET Core web app to Azure, and launches the app in your default browser.

    已发布 Azure 中运行的 ASP.NET Web 应用

祝贺你!Congratulations! 你的 ASP.NET Core Web 应用已在 Azure 应用服务中实时运行!Your ASP.NET Core web app is running live in Azure App Service.

更新应用并重新部署Update the app and redeploy

遵循以下步骤更新并重新部署 Web 应用:Follow these steps to update and redeploy your web app:

  1. 解决方案资源管理器中你的项目下,打开“页” > “Index.cshtml”。In Solution Explorer, under your project, open Pages > Index.cshtml.

  2. 将整个 <div> 标记替换为以下代码:Replace the entire <div> tag with the following code:

    <div class="jumbotron">
        <h1>ASP.NET in Azure!</h1>
        <p class="lead">This is a simple app that we've built that demonstrates how to deploy a .NET app to Azure App Service.</p>
    </div>
    
  3. 若要重新部署到 Azure,请在“解决方案资源管理器”中右键单击“myFirstAzureWebApp”项目,然后选择“发布”。To redeploy to Azure, right-click the myFirstAzureWebApp project in Solution Explorer and select Publish.

  4. 在“发布”摘要页中选择“发布” 。In the Publish summary page, select Publish.

    发布对 Web 应用的更新

发布完成后,Visual Studio 将启动浏览器并转到 Web 应用的 URL。When publishing completes, Visual Studio launches a browser to the URL of the web app.

已更新 Azure 中运行的 ASP.NET Web 应用

管理 Azure 应用Manage the Azure app

若要管理 Web 应用,请转到 Azure 门户,然后搜索并选择“应用服务”。To manage your web app, go to the Azure portal, and search for and select App Services.

选择应用服务

在“应用服务”页上,选择 Web 应用的名称。On the App Services page, select the name of your web app.

在门户中导航到 Azure 应用

Web 应用的“概述”页包含用于基本管理(例如浏览、停止、启动、重启和删除)的选项。The Overview page for your web app, contains options for basic management like browse, stop, start, restart, and delete. 左侧菜单提供用于配置应用的更多页面。The left menu provides further pages for configuring your app.

Azure 门户中的应用服务

清理资源Clean up resources

在前面的步骤中,你在资源组中创建了 Azure 资源。In the preceding steps, you created Azure resources in a resource group. 如果将来不再需要这些资源,可以通过删除资源组来删除它们。If you don't expect to need these resources in the future, you can delete them by deleting the resource group.

从 Azure 门户菜单或页中选择“资源组”, 然后在“资源组”页中选择“myResourceGroup”。 From the Azure portal menu or Home page, select Resource groups, and on the Resource groups page, select myResourceGroup.

在“myResourceGroup”页中,确保列出的资源是要删除的资源。 On the myResourceGroup page, make sure that the listed resources are the ones you want to delete.

选择“删除资源组” ,在文本框中键入“myResourceGroup” 以确认,然后选择“删除” 。Select Delete resource group, type myResourceGroup in the text box to confirm, and then select Delete.

后续步骤Next steps

在本快速入门中,你已使用 Visual Studio 创建了一个 ASP.NET Core Web 应用,并已将其部署到 Azure 应用服务。In this quickstart, you used Visual Studio to create and deploy an ASP.NET Core web app to Azure App Service.

请继续学习下一篇文章,了解如何创建 .NET Core 应用并将其连接到 SQL 数据库:Advance to the next article to learn how to create a .NET Core app and connect it to a SQL Database:

Linux 应用服务使用 Linux 操作系统,提供高度可缩放的自修补 Web 托管服务。App Service on Linux provides a highly scalable, self-patching web hosting service using the Linux operating system. 本快速入门演示如何在 Linux 应用服务中创建 .NET Core 应用。This quickstart shows how to create a .NET Core app on App Service on Linux. 使用 Azure CLI 创建应用,并使用 Git 将 .NET Core 代码部署到该应用。You create the app using the Azure CLI, and you use Git to deploy the .NET Core code to the app.

在 Azure 中运行应用的示例

可以使用 Mac、Windows 或 Linux 计算机执行本文中的步骤。You can follow the steps in this article using a Mac, Windows, or Linux machine.

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

先决条件Prerequisites

完成本快速入门教程需要:To complete this quickstart:

在本地创建应用Create the app locally

在计算机的终端窗口中,创建一个名为 hellodotnetcore 的目录,并将当前目录切换到该目录。In a terminal window on your machine, create a directory named hellodotnetcore and change the current directory to it.

mkdir hellodotnetcore
cd hellodotnetcore

创建新的 .NET Core 应用。Create a new .NET Core app.

dotnet new web

在本地运行应用Run the app locally

在本地运行应用程序,以便你能了解将它部署到 Azure 时它的外观应该是什么样的。Run the application locally so that you see how it should look when you deploy it to Azure.

还原 NuGet 包并运行该应用。Restore the NuGet packages and run the app.

dotnet run

打开 Web 浏览器并导航到 http://localhost:5000 处的应用。Open a web browser, and navigate to the app at http://localhost:5000.

页面中会显示该示例应用发出的 Hello World 消息。You see the Hello World message from the sample app displayed in the page.

使用浏览器进行测试

在终端窗口中,按 Ctrl+C 退出 Web 服务器。In your terminal window, press Ctrl+C to exit the web server. 为 .NET Core 项目初始化 Git 存储库。Initialize a Git repository for the .NET Core project.

git init
git add .
git commit -m "first commit"

创建部署用户Create a deployment user

可以使用“部署用户” 将 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 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. 例如,可以选择在使用完之后通过一个简单的步骤删除整个资源组。For example, you can choose to delete the entire resource group in one simple step later.

在 Azure CLI 中,使用 az group create 命令创建资源组。In the Azure CLI, create a resource group with the az group create command. 以下示例在“中国东部 2”位置创建名为 myResourceGroup 的资源组。**The following example creates a resource group named myResourceGroup in the China East 2 location. 若要查看基本层中 Linux 上的应用服务支持的所有位置,请运行 az appservice list-locations --sku B1 --linux-workers-enabled 命令。To see all supported locations for App Service on Linux in Basic tier, run the az appservice list-locations --sku B1 --linux-workers-enabled command.

az group create --name myResourceGroup --location "China East 2"

通常在附近的区域中创建资源组和资源。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.

Create an Azure App Service plan

在 Azure CLI 中,使用 az appservice plan create 命令在资源组中创建应用服务计划。In the Azure CLI, create an App Service plan in the resource group 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 到 10 个实例)Scale count (1 to 10 instances)
  • SKU(基本、标准)SKU (Basic, Standard)

以下示例在免费定价层 (--sku F1) 和 Linux 容器 (--is-linux) 中创建名为 myAppServicePlan 的应用服务计划。The following example creates an App Service plan named myAppServicePlan in the Free pricing tier (--sku F1) and in a Linux container (--is-linux).

az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku F1 --is-linux

创建应用服务计划后,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 East 2",
  "hostingEnvironmentProfile": null,
  "id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
  "kind": "linux",
  "location": "China East 2",
  "maximumNumberOfWorkers": 1,
  "name": "myAppServicePlan",
  < JSON data removed for brevity. >
  "targetWorkerSizeId": 0,
  "type": "Microsoft.Web/serverfarms",
  "workerTierName": null
} 

创建 Web 应用Create a web app

Create a web app in the myAppServicePlan App Service plan.

In the Azure CLI, you can use the az webapp create command. In the following example, replace <app-name> with a globally unique app name (valid characters are a-z, 0-9, and -). The runtime is set to DOTNETCORE|3.1. To see all supported runtimes, run az webapp list-runtimes --linux.

# Bash
az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app-name> --runtime "DOTNETCORE|3.1" --deployment-local-git
# PowerShell
az --% webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app-name> --runtime "DOTNETCORE|3.1" --deployment-local-git

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://@.scm.chinacloudsites.cn/.git'
{
  "availabilityState": "Normal",
  "clientAffinityEnabled": true,
  "clientCertEnabled": false,
  "cloningInfo": null,
  "containerSize": 0,
  "dailyMemoryTimeQuota": 0,
  "defaultHostName": ".chinacloudsites.cn",
  "deploymentLocalGitUrl": "https://@.scm.chinacloudsites.cn/.git",
  "enabled": true,
  < JSON data removed for brevity. >
}

You’ve created an empty web app in a Linux container, with git deployment enabled.

备注

The URL of the Git remote is shown in the deploymentLocalGitUrl property, with the format https://<username>@<app-name>.scm.chinacloudsites.cn/<app-name>.git. Save this URL as you need it later.

浏览到新建的应用。Browse to your newly created app. 将 <app name> 替换为你的应用名称 。Replace <app-name> with your app name.

https://<app-name>.chinacloudsites.cn

新应用应该如下所示:Here is what your new app should look like:

空应用页

从 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 Git Credential Manager prompts you for credentials, make sure 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:

Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 285 bytes | 95.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0), pack-reused 0
remote: Deploy Async
remote: Updating branch 'master'.
remote: Updating submodules.
remote: Preparing deployment for commit id 'd6b54472f7'.
remote: Repository path is /home/site/repository
remote: Running oryx build...
remote: Build orchestrated by Microsoft Oryx, https://github.com/Microsoft/Oryx
remote: You can report issues at https://github.com/Microsoft/Oryx/issues
remote:
remote: Oryx Version      : 0.2.20200114.13, Commit: 204922f30f8e8d41f5241b8c218425ef89106d1d, ReleaseTagName: 20200114.13
remote: Build Operation ID: |imoMY2y77/s=.40ca2a87_
remote: Repository Commit : d6b54472f7e8e9fd885ffafaa64522e74cf370e1
.
.
.
remote: Deployment successful.
remote: Deployment Logs : 'https://<app-name>.scm.chinacloudsites.cn/newui/jsonviewer?view_url=/api/deployments/d6b54472f7e8e9fd885ffafaa64522e74cf370e1/log'
To https://<app-name>.scm.chinacloudsites.cn:443/<app-name>.git
   d87e6ca..d6b5447  master -> master

浏览到应用Browse to the app

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

http://<app_name>.chinacloudsites.cn

.NET Core 示例代码在包含内置映像的 Linux 上的应用服务中运行。The .NET Core sample code is running in App Service on Linux with a built-in image.

在 Azure 中运行应用的示例

祝贺你! Congratulations! 现已将第一个 .NET Core 应用部署到 Linux 应用服务。You've deployed your first .NET Core app to App Service on Linux.

更新并重新部署代码Update and redeploy the code

在本地目录中,打开 Startup.cs 文件 。In the local directory, open the Startup.cs file. 对方法调用 context.Response.WriteAsync 中的文本稍作更改:Make a small change to the text in the method call context.Response.WriteAsync:

await context.Response.WriteAsync("Hello Azure!");

提交在 Git 中所做的更改,然后将代码更改推送到 Azure。Commit your changes in Git, and then push the code changes to Azure.

git commit -am "updated output"
git push azure master

完成部署后,切换回在“浏览到应用” 步骤中打开的浏览器窗口,并点击“刷新”。Once deployment has completed, switch back to the browser window that opened in the Browse to the app step, and hit refresh.

已更新的在 Azure 中运行应用的示例

管理新的 Azure 应用Manage your new Azure app

转到 Azure 门户管理已创建的应用。Go to the Azure portal to manage the app you created.

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

在门户中导航到 Azure 应用

这里我们可以看到应用的“概述”页。You see your app's Overview page. 并可以执行基本的管理任务,例如浏览、停止、启动、重新启动和删除。Here, you can perform basic management tasks like browse, stop, start, restart, and delete.

Azure 门户中的应用服务页

左侧菜单提供了用于配置应用的不同页面。The left menu provides different pages for configuring your app.

清理资源Clean up resources

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

az group delete --name myResourceGroup

后续步骤Next steps