用于 ASP.NET Core 应用部署的 Visual Studio 发布配置文件Visual Studio publish profiles for ASP.NET Core app deployment

作者:Sayed Ibrahim HashimiRick AndersonBy Sayed Ibrahim Hashimi and Rick Anderson

本文档重点介绍了如何通过 Visual Studio 2019 或更高版本创建和使用发布配置文件。This document focuses on using Visual Studio 2019 or later to create and use publish profiles. 通过 Visual Studio 创建的发布配置文件可用于 MSBuild 和 Visual Studio。The publish profiles created with Visual Studio can be used with MSBuild and Visual Studio. 要查看说明了解如何发布到 Azure,请参阅 使用 Visual Studio 将 ASP.NET Core 应用发布到 AzureFor instructions on publishing to Azure, see 使用 Visual Studio 将 ASP.NET Core 应用发布到 Azure.

dotnet new mvc 命令会生成包含以下根级 <Project> 元素的项目文件:The dotnet new mvc command produces a project file containing the following root-level <Project> element:

<Project Sdk="Microsoft.NET.Sdk.Web">
    <!-- omitted for brevity -->
</Project>

前导 <Project> 元素的 Sdk 属性分别从 $(MSBuildSDKsPath)\Microsoft.NET.Sdk.Web\Sdk\Sdk.props 和 $(MSBuildSDKsPath)\Microsoft.NET.Sdk.Web\Sdk\Sdk.targets 导入 MSBuild 属性目标The preceding <Project> element's Sdk attribute imports the MSBuild properties and targets from $(MSBuildSDKsPath)\Microsoft.NET.Sdk.Web\Sdk\Sdk.props and $(MSBuildSDKsPath)\Microsoft.NET.Sdk.Web\Sdk\Sdk.targets, respectively. $(MSBuildSDKsPath)(装有 Visual Studio 2019 Enterprise)的默认位置是 %programfiles(x86)%\Microsoft Visual Studio\2019\Enterprise\MSBuild\Sdks 文件夹。The default location for $(MSBuildSDKsPath) (with Visual Studio 2019 Enterprise) is the %programfiles(x86)%\Microsoft Visual Studio\2019\Enterprise\MSBuild\Sdks folder.

Microsoft.NET.Sdk.Web (Web SDK) 依赖于其他 SDK,包括 Microsoft.NET.Sdk (.NET Core SDK) 和 Microsoft.NET.Sdk.Razor (Razor SDK)。Microsoft.NET.Sdk.Web (Web SDK) depends on other SDKs, including Microsoft.NET.Sdk (.NET Core SDK) and Microsoft.NET.Sdk.Razor (Razor SDK). 将导入与每个从属 SDK 关联的 MSBuild 属性和目标。The MSBuild properties and targets associated with each dependent SDK are imported. 发布目标将根据使用的发布方法,导入相应的目标集。Publish targets import the appropriate set of targets based on the publish method used.

MSBuild 或 Visual Studio 加载项目时,执行下列高级别操作:When MSBuild or Visual Studio loads a project, the following high-level actions occur:

  • 生成项目Build project
  • 计算要发布的文件Compute files to publish
  • 将文件发布到目标Publish files to destination

计算项目项Compute project items

加载项目时,将计算 MSBuild 项目项(文件)。When the project is loaded, the MSBuild project items (files) are computed. 项类型确定如何处理该文件。The item type determines how the file is processed. 默认情况下,.cs 文件包含在 Compile 项列表内。By default, .cs files are included in the Compile item list. 会对 Compile 项列表中的文件进行编译。Files in the Compile item list are compiled.

除了生成输出,Content 项列表还包含已发布的文件。The Content item list contains files that are published in addition to the build outputs. 默认情况下,匹配模式 wwwroot\****\*.config**\*.json 的文件包含在 Content 项列表内。By default, files matching the patterns wwwroot\**, **\*.config, and **\*.json are included in the Content item list. 例如,wwwroot\** glob 模式与 wwwroot 文件夹及其子文件夹中的所有文件相匹配 。For example, the wwwroot\** globbing pattern matches all files in the wwwroot folder and its subfolders.

Web SDK 导入 Razor SDKThe Web SDK imports the Razor SDK. 因此,匹配模式 **\*.cshtml**\*.razor 的文件也同时包含在 Content 项列表内。As a result, files matching the patterns **\*.cshtml and **\*.razor are also included in the Content item list.

Web SDK 导入 Razor SDKThe Web SDK imports the Razor SDK. 因此,匹配 **\*.cshtml 模式的文件也同时包含在 Content 项列表内。As a result, files matching the **\*.cshtml pattern are also included in the Content item list.

若要将文件显式添加到发布列表,请直接在 .csproj 文件中添加文件,如包含文件一节中所示。To explicitly add a file to the publish list, add the file directly in the .csproj file as shown in the Include Files section.

在 Visual Studio 中选择“发布” 按钮时或从命令行发布时:When selecting the Publish button in Visual Studio or when publishing from the command line:

  • 计算属性/项目(需要生成的文件)。The properties/items are computed (the files that are needed to build).
  • 仅限 Visual Studio:NuGet 包已还原。Visual Studio only: NuGet packages are restored. (用户需要在 CLI 上执行显式还原。)(Restore needs to be explicit by the user on the CLI.)
  • 生成项目。The project builds.
  • 计算发布项(需要发布的文件)。The publish items are computed (the files that are needed to publish).
  • 文件已发布(计算的文件将被复制到发布目标)。The project is published (the computed files are copied to the publish destination).

当 ASP.NET Core 项目在项目文件中引用 Microsoft.NET.Sdk.Web 时,会将 app_offline.htm 文件放在 Web 应用目录的根目录下。When an ASP.NET Core project references Microsoft.NET.Sdk.Web in the project file, an app_offline.htm file is placed at the root of the web app directory. 该文件存在时,ASP.NET Core 模块会在部署过程中正常关闭该应用并提供 app_offline.htm 文件 。When the file is present, the ASP.NET Core Module gracefully shuts down the app and serves the app_offline.htm file during the deployment. 有关详细信息,请参阅 ASP.NET Core 模块配置参考For more information, see the ASP.NET Core Module configuration reference.

基本命令行发布Basic command-line publishing

命令行发布适用于所有支持 .NET Core 的平台,而且不需要 Visual Studio。Command-line publishing works on all .NET Core-supported platforms and doesn't require Visual Studio. 在下面的示例中,从项目目录(其中包含 .csproj文件)运行 .NET Core CLI 的 dotnet publish 命令 。In the following examples, the .NET Core CLI's dotnet publish command is run from the project directory (which contains the .csproj file). 如果当前工作目录中没有项目文件夹,则在项目文件路径中显式传递。If the project folder isn't the current working directory, explicitly pass in the project file path. 例如:For example:

dotnet publish C:\Webs\Web1

运行以下命令以创建并发布 Web 应用:Run the following commands to create and publish a web app:

dotnet new mvc
dotnet publish

dotnet publish 会生成以下输出的变体:The dotnet publish command produces a variation of the following output:

C:\Webs\Web1>dotnet publish
Microsoft (R) Build Engine version {VERSION} for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  Restore completed in 36.81 ms for C:\Webs\Web1\Web1.csproj.
  Web1 -> C:\Webs\Web1\bin\Debug\{TARGET FRAMEWORK MONIKER}\Web1.dll
  Web1 -> C:\Webs\Web1\bin\Debug\{TARGET FRAMEWORK MONIKER}\Web1.Views.dll
  Web1 -> C:\Webs\Web1\bin\Debug\{TARGET FRAMEWORK MONIKER}\publish\

默认发布文件夹格式为 bin\Debug\{TARGET FRAMEWORK MONIKER}\publish\ 。The default publish folder format is bin\Debug\{TARGET FRAMEWORK MONIKER}\publish\. 例如 bin\Debug\netcoreapp2.2\publish\ 。For example, bin\Debug\netcoreapp2.2\publish\.

以下命令指定 Release 生成和发布目录:The following command specifies a Release build and the publishing directory:

dotnet publish -c Release -o C:\MyWebs\test

dotnet publish 命令调用 MSBuild,后者会调用 Publish 目标。The dotnet publish command calls MSBuild, which invokes the Publish target. 任何传递给 dotnet publish 的参数都将传递给 MSBuild。Any parameters passed to dotnet publish are passed to MSBuild. -c-o 参数分别映射到 MSBuild 的 ConfigurationOutputPath 属性。The -c and -o parameters map to MSBuild's Configuration and OutputPath properties, respectively.

可以使用以下任一格式来传递 MSBuild 属性:MSBuild properties can be passed using either of the following formats:

  • p:<NAME>=<VALUE>
  • /p:<NAME>=<VALUE>

例如,以下命令将 Release 版本发布到网络共享。For example, the following command publishes a Release build to a network share. 网络共享通过正斜杠指定 (//r8/ ) 并适用于所有支持 .NET Core 的平台。The network share is specified with forward slashes (//r8/) and works on all .NET Core supported platforms.

dotnet publish -c Release /p:PublishDir=//r8/release/AdminWeb

确认用于部署的发布应用未在运行。Confirm that the published app for deployment isn't running. 如果应用正在运行,publish 文件夹中的文件会被锁定 。Files in the publish folder are locked when the app is running. 部署不会发生,因为无法复制锁定的文件。Deployment can't occur because locked files can't be copied.

发布配置文件Publish profiles

本部分使用 Visual Studio 2019 或更高版本来创建发布配置文件。This section uses Visual Studio 2019 or later to create a publishing profile. 创建配置文件后,可以从 Visual Studio 或命令行进行发布。Once the profile is created, publishing from Visual Studio or the command line is available. 发布配置文件可以简化发布过程,并且可以存在任意数量的配置文件。Publish profiles can simplify the publishing process, and any number of profiles can exist.

通过选择以下路径之一在 Visual Studio 中创建发布配置文件:Create a publish profile in Visual Studio by choosing one of the following paths:

  • 在“解决方案资源管理器” 中,右键单击该项目并选择“发布” 。Right-click the project in Solution Explorer and select Publish.
  • 可以从“生成”菜单中选择“发布 {项目名称}” 。Select Publish {PROJECT NAME} from the Build menu.

随即显示应用程序容量页的“发布”选项卡 。The Publish tab of the app capabilities page is displayed. 如果项目缺少发布配置文件,将显示“选择发布目标”页面 。If the project lacks a publish profile, the Pick a publish target page is displayed. 系统会要求选择下述发布目标之一:You're asked to select one of the following publish targets:

  • Azure 应用服务Azure App Service
  • Linux 上的 Azure 应用服务Azure App Service on Linux
  • Azure 虚拟机Azure Virtual Machines
  • 文件夹Folder
  • IIS、FTP、Web 部署(面向任何 Web 服务器)IIS, FTP, Web Deploy (for any web server)
  • 导入配置文件Import Profile

要确定最适合的发布目标,请参阅哪些发布选项适合我To determine the most appropriate publish target, see What publishing options are right for me.

当选择“文件夹”发布目标时,指定一个文件夹路径来存储发布的资产 。When the Folder publish target is selected, specify a folder path to store the published assets. 默认文件夹路径为 bin\{PROJECT CONFIGURATION}\{TARGET FRAMEWORK MONIKER}\publish\ 。The default folder path is bin\{PROJECT CONFIGURATION}\{TARGET FRAMEWORK MONIKER}\publish\. 例如 bin\Release\netcoreapp2.2\publish\ 。For example, bin\Release\netcoreapp2.2\publish\. 选择“创建配置文件”按钮完成操作 。Select the Create Profile button to finish.

创建发布配置文件后,“发布”选项卡的内容将更改 。Once a publish profile is created, the Publish tab's content changes. 新创建的配置文件显示在下拉列表中。The newly created profile appears in a drop-down list. 在下拉列表中,选择“创建新配置文件”,再新建一个配置文件 。Below the drop-down list, select Create new profile to create another new profile.

Visual Studio 的生成工具会生成一个 Properties/PublishProfiles/{PROFILE NAME}.pubxml MSBuild 文件,它描述了发布配置文件 。Visual Studio's publish tool produces a Properties/PublishProfiles/{PROFILE NAME}.pubxml MSBuild file describing the publish profile. .pubxml 文件 :The .pubxml file:

  • 包含发布配置设置并由发布过程使用。Contains publish configuration settings and is consumed by the publishing process.
  • 可更改它来自定义生成和发布过程。Can be modified to customize the build and publish process.

发布到 Azure 目标时,.pubxml 文件包含 Azure 订阅标识符。When publishing to an Azure target, the .pubxml file contains your Azure subscription identifier. 不建议使用该目标类型将此文件添加到源代码管理。With that target type, adding this file to source control is discouraged. 发布到非 Azure 目标时,签入 .pubxml 文件是安全的。When publishing to a non-Azure target, it's safe to check in the .pubxml file.

敏感信息(如发布密码)在每个用户/机器级别均进行加密。Sensitive information (like the publish password) is encrypted on a per user/machine level. 它存储在 Properties/PublishProfiles/{PROFILE NAME}.pubxml.user 文件中 。It's stored in the Properties/PublishProfiles/{PROFILE NAME}.pubxml.user file. 由于此文件可以存储敏感信息,因此不应将其签入源代码管理。Because this file can store sensitive information, it shouldn't be checked into source control.

要简要了解如何发布 ASP.NET Core Web 应用,请参阅 托管和部署 ASP.NET CoreFor an overview of how to publish an ASP.NET Core web app, see 托管和部署 ASP.NET Core. 发布 ASP.NET Core Web 应用所需的 MSBuild 任务和目标已在 aspnet/websdk repository 上开源。The MSBuild tasks and targets necessary to publish an ASP.NET Core web app are open-source at the aspnet/websdk repository.

dotnet publish 命令可使用文件夹、MSDeploy 和 Kudu 发布配置文件。The dotnet publish command can use folder, MSDeploy, and Kudu publish profiles. MSDeploy 缺少跨平台支持,因此仅支持在 Windows 上使用以下 MSDeploy 选项。Because MSDeploy lacks cross-platform support, the following MSDeploy options are supported only on Windows.

文件夹(跨平台工作) :Folder (works cross-platform):

dotnet publish WebApplication.csproj /p:PublishProfile=<FolderProfileName>

MSDeploy :MSDeploy:

dotnet publish WebApplication.csproj /p:PublishProfile=<MsDeployProfileName> /p:Password=<DeploymentPassword>

MSDeploy 包 :MSDeploy package:

dotnet publish WebApplication.csproj /p:PublishProfile=<MsDeployPackageProfileName>

在前面的示例中,不会将 deployonbuild 传递到 dotnet publishIn the preceding examples, don't pass deployonbuild to dotnet publish.

有关详细信息,请参阅 Microsoft.NET.Sdk.PublishFor more information, see Microsoft.NET.Sdk.Publish.

dotnet publish 支持 Kudu API 从任何平台发布到 Azure。dotnet publish supports Kudu APIs to publish to Azure from any platform. Visual Studio 发布支持 Kudu API,但 WebSDK 支持其跨平台发布到 Azure。Visual Studio publish supports the Kudu APIs, but it's supported by WebSDK for cross-platform publish to Azure.

向项目的 Properties/PublishProfiles 文件夹添加包含以下内容的发布配置文件 :Add a publish profile to the project's Properties/PublishProfiles folder with the following content:

<Project>
  <PropertyGroup>
    <PublishProtocol>Kudu</PublishProtocol>
    <PublishSiteName>nodewebapp</PublishSiteName>
    <UserName>username</UserName>
    <Password>password</Password>
  </PropertyGroup>
</Project>

运行以下命令将会压缩发布内容并将其发布到使用 Kudu API 的 Azure:Run the following command to zip up the publish contents and publish it to Azure using the Kudu APIs:

dotnet publish /p:PublishProfile=Azure /p:Configuration=Release

使用发布配置文件时,请设置以下 MSBuild 属性:Set the following MSBuild properties when using a publish profile:

  • DeployOnBuild=true
  • PublishProfile={PUBLISH PROFILE}

发布名为 FolderProfile 的配置文件时,可以执行以下命令之一:When publishing with a profile named FolderProfile, either of the commands below can be executed:

  • dotnet build /p:DeployOnBuild=true /p:PublishProfile=FolderProfile
  • msbuild /p:DeployOnBuild=true /p:PublishProfile=FolderProfile

.NET Core CLI 的 dotnet build 命令会调用 msbuild 来运行生成和发布过程。The .NET Core CLI's dotnet build command calls msbuild to run the build and publish process. 在文件夹配置文件中传递时,dotnet buildmsbuild 命令作用相同。The dotnet build and msbuild commands are equivalent when passing in a folder profile. 在 Windows 上直接调用 msbuild 时,将使用 MSBuild 的 .NET Framework 版本。When calling msbuild directly on Windows, the .NET Framework version of MSBuild is used. 在非文件夹配置文件上调用 dotnet buildCalling dotnet build on a non-folder profile:

  • 调用 msbuild后者使用 MSDeploy。Invokes msbuild, which uses MSDeploy.
  • 结果失败(即使在 Windows 上运行时)。Results in a failure (even when running on Windows). 要使用非文件夹配置文件发布,请直接调用 msbuildTo publish with a non-folder profile, call msbuild directly.

以下文件夹发布配置文件通过 Visual Studio 创建,并被发布到网络共享:The following folder publish profile was created with Visual Studio and publishes to a network share:

<?xml version="1.0" encoding="utf-8"?>
<!--
This file is used by the publish/package process of your Web project.
You can customize the behavior of this process by editing this 
MSBuild file.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <WebPublishMethod>FileSystem</WebPublishMethod>
    <PublishProvider>FileSystem</PublishProvider>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish />
    <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
    <ExcludeApp_Data>False</ExcludeApp_Data>
    <PublishFramework>netcoreapp1.1</PublishFramework>
    <ProjectGuid>c30c453c-312e-40c4-aec9-394a145dee0b</ProjectGuid>
    <publishUrl>\\r8\Release\AdminWeb</publishUrl>
    <DeleteExistingFiles>False</DeleteExistingFiles>
  </PropertyGroup>
</Project>

在上面的示例中:In the preceding example:

  • <ExcludeApp_Data> 属性仅为满足 XML 架构要求。The <ExcludeApp_Data> property is present merely to satisfy an XML schema requirement. <ExcludeApp_Data> 属性不影响发布过程,即使项目根中存在 App_Data 文件夹也是如此 。The <ExcludeApp_Data> property has no effect on the publish process, even if there's an App_Data folder in the project root. App_Data 文件夹不会像在 ASP.NET 4.x 项目中那样得到特殊对待 。The App_Data folder doesn't receive special treatment as it does in ASP.NET 4.x projects.

  • <LastUsedBuildConfiguration> 属性设置为 ReleaseThe <LastUsedBuildConfiguration> property is set to Release. 从 Visual Studio 发布时,启动发布过程后将使用该值设置 <LastUsedBuildConfiguration> 的值。When publishing from Visual Studio, the value of <LastUsedBuildConfiguration> is set using the value when the publish process is started. <LastUsedBuildConfiguration> 比较特殊,不得在导入的 MSBuild 文件中覆盖它。<LastUsedBuildConfiguration> is special and shouldn't be overridden in an imported MSBuild file. 但是,可通过下述方法之一在命令行中覆盖此属性。This property can, however, be overridden from the command line using one of the following approaches.

    • 使用 .NET Core CLI:Using the .NET Core CLI:

      dotnet build -c Release /p:DeployOnBuild=true /p:PublishProfile=FolderProfile
      
    • 使用 MSBuild:Using MSBuild:

      msbuild /p:Configuration=Release /p:DeployOnBuild=true /p:PublishProfile=FolderProfile
      

    有关详细信息,请参阅 MSBuild:如何设置配置属性For more information, see MSBuild: how to set the configuration property.

从命令行发布到 MSDeploy 终结点Publish to an MSDeploy endpoint from the command line

下面的示例使用由 Visual Studio 创建的 ASP.NET Core Web 应用,名为 AzureWebApp 。The following example uses an ASP.NET Core web app created by Visual Studio named AzureWebApp. 通过 Visual Studio 添加 Azure 应用发布配置文件。An Azure Apps publish profile is added with Visual Studio. 有关如何创建配置文件的详细信息,请参阅发布配置文件部分。For more information on how to create a profile, see the Publish profiles section.

若要使用发布配置文件部署应用,请在 Visual Studio 开发人员命令提示中执行 msbuild 命令 。To deploy the app using a publish profile, execute the msbuild command from a Visual Studio Developer Command Prompt. Windows 任务栏上的“开始”菜单的“Visual Studio”文件夹中提供命令提示符 。The command prompt is available in the Visual Studio folder of the Start menu on the Windows taskbar. 为了便于访问,可将命令提示符添加到 Visual Studio 中的“工具”菜单中 。For easier access, you can add the command prompt to the Tools menu in Visual Studio. 有关详细信息,请参阅 Visual Studio 开发人员命令提示符For more information, see Developer Command Prompt for Visual Studio.

MSBuild 使用以下命令语法:MSBuild uses the following command syntax:

msbuild {PATH} 
    /p:DeployOnBuild=true 
    /p:PublishProfile={PROFILE} 
    /p:Username={USERNAME} 
    /p:Password={PASSWORD}
  • {PATH} – 应用的项目文件路径。{PATH} – Path to the app's project file.
  • {PROFILE} – 发布配置文件的名称。{PROFILE} – Name of the publish profile.
  • {USERNAME} – MSDeploy 用户名。{USERNAME} – MSDeploy username. 可在发布配置文件中找到 {USERNAME}。The {USERNAME} can be found in the publish profile.
  • {PASSWORD} – MSDeploy 密码。{PASSWORD} – MSDeploy password. 从 {PROFILE}.PublishSettings 文件中获取 {PASSWORD} 。Obtain the {PASSWORD} from the {PROFILE}.PublishSettings file. 可以从以下位置下载 .PublishSettings 文件:Download the .PublishSettings file from either:
    • 解决方案资源管理器 :选择“视图” > “Cloud Explorer” 。Solution Explorer: Select View > Cloud Explorer. 连接你的 Azure 订阅。Connect with your Azure subscription. 打开“应用服务” 。Open App Services. 右键单击应用。Right-click the app. 选择“下载发布配置文件” 。Select Download Publish Profile.
    • Azure 门户:选择 Web 应用“概述”面板上的“获取发布配置文件” 。Azure portal: Select Get publish profile in the web app's Overview panel.

下面的示例使用名为“AzureWebApp - Web 部署”的发布配置文件 :The following example uses a publish profile named AzureWebApp - Web Deploy:

msbuild "AzureWebApp.csproj" 
    /p:DeployOnBuild=true 
    /p:PublishProfile="AzureWebApp - Web Deploy" 
    /p:Username="$AzureWebApp" 
    /p:Password=".........."

发布配置文件还可通过 Windows 命令行界面与 .NET Core CLI 的 dotnet msbuild 一起使用:A publish profile can also be used with the .NET Core CLI's dotnet msbuild command from a Windows command shell:

dotnet msbuild "AzureWebApp.csproj"
    /p:DeployOnBuild=true 
    /p:PublishProfile="AzureWebApp - Web Deploy" 
    /p:Username="$AzureWebApp" 
    /p:Password=".........."

重要

dotnet msbuild 命令是一个跨平台命令,可在 macOS 和 Linux 上编译 ASP.NET Core 应用。The dotnet msbuild command is a cross-platform command and can compile ASP.NET Core apps on macOS and Linux. 但是,macOS 和 Linux 上的 MSBuild 不能将应用部署到 Azure 或其他 MSDeploy 终结点。However, MSBuild on macOS and Linux isn't capable of deploying an app to Azure or other MSDeploy endpoints.

设置环境Set the environment

<EnvironmentName> 属性包含在发布配置文件(.pubxml )或项目文件中,以设置应用的环境Include the <EnvironmentName> property in the publish profile (.pubxml) or project file to set the app's environment:

<PropertyGroup>
  <EnvironmentName>Development</EnvironmentName>
</PropertyGroup>

如果需要 web.config 转换(例如,基于配置、配置文件或环境设置环境变量),请参阅 转换 web.configIf you require web.config transformations (for example, setting environment variables based on the configuration, profile, or environment), see 转换 web.config.

排除文件Exclude files

在发布 ASP.NET Core Web 应用时,包括以下资产:When publishing ASP.NET Core web apps, the following assets are included:

  • 生成工件Build artifacts
  • 与以下 glob 模式匹配的文件夹和文件:Folders and files matching the following globbing patterns:
    • **\*.config(例如,web.config )**\*.config (for example, web.config)
    • **\*.json(例如,appsettings.json )**\*.json (for example, appsettings.json)
    • wwwroot\**

MSBuild 支持 glob 模式MSBuild supports globbing patterns. 例如,以下 <Content> 元素禁止在 wwwroot\content 文件夹及其子文件夹中复制文本 (.txt ) 文件:For example, the following <Content> element suppresses the copying of text (.txt) files in the wwwroot\content folder and its subfolders:

<ItemGroup>
  <Content Update="wwwroot/content/**/*.txt" CopyToPublishDirectory="Never" />
</ItemGroup>

可以将上面的标记添加到发布配置文件或 .csproj 文件。The preceding markup can be added to a publish profile or the .csproj file. 添加到 .csproj 文件时,会将该规则添加到项目中的所有发布配置文件中。When added to the .csproj file, the rule is added to all publish profiles in the project.

以下 <MsDeploySkipRules> 元素排除 wwwroot\content 文件夹中的所有文件:The following <MsDeploySkipRules> element excludes all files from the wwwroot\content folder:

<ItemGroup>
  <MsDeploySkipRules Include="CustomSkipFolder">
    <ObjectName>dirPath</ObjectName>
    <AbsolutePath>wwwroot\\content</AbsolutePath>
  </MsDeploySkipRules>
</ItemGroup>

<MsDeploySkipRules> 不会从部署站点删除跳过 目标。<MsDeploySkipRules> won't delete the skip targets from the deployment site. 从部署站点中删除 <Content> 目标文件和文件夹。<Content> targeted files and folders are deleted from the deployment site. 例如,假设部署的 Web 应用具有以下文件:For example, suppose a deployed web app had the following files:

  • Views/Home/About1.cshtmlViews/Home/About1.cshtml
  • Views/Home/About2.cshtmlViews/Home/About2.cshtml
  • Views/Home/About3.cshtmlViews/Home/About3.cshtml

如果添加了以下 <MsDeploySkipRules> 元素,则不会在部署站点上删除这些文件。If the following <MsDeploySkipRules> elements are added, those files wouldn't be deleted on the deployment site.

<ItemGroup>
  <MsDeploySkipRules Include="CustomSkipFile">
    <ObjectName>filePath</ObjectName>
    <AbsolutePath>Views\\Home\\About1.cshtml</AbsolutePath>
  </MsDeploySkipRules>

  <MsDeploySkipRules Include="CustomSkipFile">
    <ObjectName>filePath</ObjectName>
    <AbsolutePath>Views\\Home\\About2.cshtml</AbsolutePath>
  </MsDeploySkipRules>

  <MsDeploySkipRules Include="CustomSkipFile">
    <ObjectName>filePath</ObjectName>
    <AbsolutePath>Views\\Home\\About3.cshtml</AbsolutePath>
  </MsDeploySkipRules>
</ItemGroup>

之前的 <MsDeploySkipRules> 元素阻止部署跳过的 文件。The preceding <MsDeploySkipRules> elements prevent the skipped files from being deployed. 一旦部署这些文件就不会删除它们。It won't delete those files once they're deployed.

以下 <Content> 元素将在部署站点中删除目标文件:The following <Content> element deletes the targeted files at the deployment site:

<ItemGroup>
  <Content Update="Views/Home/About?.cshtml" CopyToPublishDirectory="Never" />
</ItemGroup>

如果将命令行部署和前面的 <Content> 元素一起使用,则将生成以下输出的变体:Using command-line deployment with the preceding <Content> element yields a variation of the following output:

MSDeployPublish:
  Starting Web deployment task from source: manifest(C:\Webs\Web1\obj\Release\{TARGET FRAMEWORK MONIKER}\PubTmp\Web1.SourceManifest.
  xml) to Destination: auto().
  Deleting file (Web11112\Views\Home\About1.cshtml).
  Deleting file (Web11112\Views\Home\About2.cshtml).
  Deleting file (Web11112\Views\Home\About3.cshtml).
  Updating file (Web11112\web.config).
  Updating file (Web11112\Web1.deps.json).
  Updating file (Web11112\Web1.dll).
  Updating file (Web11112\Web1.pdb).
  Updating file (Web11112\Web1.runtimeconfig.json).
  Successfully executed Web deployment task.
  Publish Succeeded.
Done Building Project "C:\Webs\Web1\Web1.csproj" (default targets).

包含文件Include files

下列各部分简要介绍了发布时用于包含文件的不同方法。The following sections outline different approaches for file inclusion at publish time. 常规文件包含部分使用了 DotNetPublishFiles 项,后者由 Web SDK 中的发布目标文件提供。The General file inclusion section uses the DotNetPublishFiles item, which is provided by a publish targets file in the Web SDK. 选择性文件包含部分使用的是 ResolvedFileToPublish 项,它由 .NET Core SDK 中的发布目标文件提供。The Selective file inclusion section uses the ResolvedFileToPublish item, which is provided by a publish targets file in the .NET Core SDK. Web SDK 依赖于 .NET Core SDK,因此上述任一项都可在 ASP.NET Core 项目中使用。Because the Web SDK depends on the .NET Core SDK, either item can be used in an ASP.NET Core project.

常规文件包含General file inclusion

下例中的 <ItemGroup> 元素展示了将位于项目目录之外的文件夹复制到已发布的站点的文件夹中。The following example's <ItemGroup> element demonstrates copying a folder located outside of the project directory to a folder of the published site. 添加到下述标记的 <ItemGroup> 的所有文件都将默认包含在内。Any files added to the following markup's <ItemGroup> are included by default.

<ItemGroup>
  <_CustomFiles Include="$(MSBuildProjectDirectory)/../images/**/*" />
  <DotNetPublishFiles Include="@(_CustomFiles)">
    <DestinationRelativePath>wwwroot/images/%(RecursiveDir)%(Filename)%(Extension)</DestinationRelativePath>
  </DotNetPublishFiles>
</ItemGroup>

前面的标记:The preceding markup:

  • 可以将标记添加到 .csproj 文件或发布配置文件。Can be added to the .csproj file or the publish profile. 如果将其添加到 .csproj 文件,它会包含在项目的每个发布配置文件中。If it's added to the .csproj file, it's included in each publish profile in the project.
  • 声明一个 _CustomFiles 项来存储与 Include 属性的 glob 模式匹配的文件。Declares a _CustomFiles item to store files matching the Include attribute's globbing pattern. 模式中引用的“图像”文件夹未在项目目录中 。The images folder referenced in the pattern is located outside of the project directory. 名为 $(MSBuildProjectDirectory)保留属性会解析为项目文件的绝对路径。A reserved property, named $(MSBuildProjectDirectory), resolves to the project file's absolute path.
  • DotNetPublishFiles 项提供一个文件列表。Provides a list of files to the DotNetPublishFiles item. 默认情况下,该项的 <DestinationRelativePath> 元素为空。By default, the item's <DestinationRelativePath> element is empty. 默认值在标记中重写,且使用 %(RecursiveDir)常见的项元数据The default value is overridden in the markup and uses well-known item metadata such as %(RecursiveDir). 内部文本表示已发布的站点的 wwwroot/images 文件夹 。The inner text represents the wwwroot/images folder of the published site.

选择性文件包含Selective file inclusion

下例中突出显示的标记展示了:The highlighted markup in the following example demonstrates:

  • 将项目之外的文件复制到已发布的站点的 wwwroot 文件夹 。Copying a file located outside of the project into the published site's wwwroot folder. 保留文件名 ReadMe2.md 。The file name of ReadMe2.md is maintained.
  • 排除 wwwroot\Content 文件夹 。Excluding the wwwroot\Content folder.
  • 排除 Views\Home\About2.cshtml 。Excluding Views\Home\About2.cshtml.
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" 
         xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <WebPublishMethod>FileSystem</WebPublishMethod>
    <PublishProvider>FileSystem</PublishProvider>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish />
    <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
    <ExcludeApp_Data>False</ExcludeApp_Data>
    <PublishFramework />
    <ProjectGuid>afa9f185-7ce0-4935-9da1-ab676229d68a</ProjectGuid>
    <publishUrl>bin\Release\PublishOutput</publishUrl>
    <DeleteExistingFiles>False</DeleteExistingFiles>
  </PropertyGroup>
  <ItemGroup>
    <ResolvedFileToPublish Include="..\ReadMe2.md">
      <RelativePath>wwwroot\ReadMe2.md</RelativePath>
    </ResolvedFileToPublish>

    <Content Update="wwwroot\Content\**\*" CopyToPublishDirectory="Never" />
    <Content Update="Views\Home\About2.cshtml" CopyToPublishDirectory="Never" />
  </ItemGroup>
</Project>

前述示例使用 ResolvedFileToPublish 项,其默认行为是始终将 Include 中提供的文件复制到已发布的站点中。The preceding example uses the ResolvedFileToPublish item, whose default behavior is to always copy the files provided in the Include attribute to the published site. 通过 NeverPreserveNewest 的内部文本包含 <CopyToPublishDirectory>覆盖默认行为。Override the default behavior by including a <CopyToPublishDirectory> child element with inner text of either Never or PreserveNewest. 例如:For example:

<ResolvedFileToPublish Include="..\ReadMe2.md">
  <RelativePath>wwwroot\ReadMe2.md</RelativePath>
  <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</ResolvedFileToPublish>

有关更多部署示例,请参阅 Web SDK 存储库自述文件For more deployment samples, see the Web SDK repository Readme.

在发布前或发布后运行目标Run a target before or after publishing

内置 BeforePublishAfterPublish 目标在发布目标前/后执行目标。The built-in BeforePublish and AfterPublish targets execute a target before or after the publish target. 将以下元素添加到发布配置文件,以在发布前/后均记录控制台消息:Add the following elements to the publish profile to log console messages both before and after publishing:

<Target Name="CustomActionsBeforePublish" BeforeTargets="BeforePublish">
    <Message Text="Inside BeforePublish" Importance="high" />
  </Target>
  <Target Name="CustomActionsAfterPublish" AfterTargets="AfterPublish">
    <Message Text="Inside AfterPublish" Importance="high" />
</Target>

使用不受信任的证书发布到服务器Publish to a server using an untrusted certificate

将值为 True<AllowUntrustedCertificate> 属性添加到发布配置文件:Add the <AllowUntrustedCertificate> property with a value of True to the publish profile:

<PropertyGroup>
  <AllowUntrustedCertificate>True</AllowUntrustedCertificate>
</PropertyGroup>

Kudu 服务The Kudu service

要查看 Azure 应用服务 Web 应用部署中的文件,请使用 Kudu 服务To view the files in an Azure App Service web app deployment, use the Kudu service. scm 令牌追加到 Web 应用名称。Append the scm token to the web app name. 例如:For example:

URLURL 结果Result
http://mysite.azurewebsites.net/ Web 应用Web App
http://mysite.scm.azurewebsites.net/ Kudu 服务Kudu service

选择调试控制台菜单项来查看、编辑、删除或添加文件。Select the Debug Console menu item to view, edit, delete, or add files.

其他资源Additional resources