用于 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 2017 或更高版本创建并使用发布配置文件。This document focuses on using Visual Studio 2017 or later to create and use publish profiles. 可以从 MSBuild 和 Visual Studio 运行使用 Visual Studio 创建的发布配置文件。The publish profiles created with Visual Studio can be run from MSBuild and Visual Studio. 有关发布到 Azure 的说明,请参阅使用 Visual Studio 将 ASP.NET Core Web 应用发布到 Azure App ServiceSee Publish an ASP.NET Core web app to Azure App Service using Visual Studio for instructions on publishing to Azure.

使用命令 dotnet new mvc 创建以下项目文件:The following project file was created with the command dotnet new mvc:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>

</Project>
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>

</Project>

<Project> 元素的 Sdk 属性完成以下任务:The <Project> element's Sdk attribute accomplishes the following tasks:

  • 在开始时从 $(MSBuildSDKsPath)\Microsoft.NET.Sdk.Web\Sdk\Sdk.Props 导入属性文件。Imports the properties file from $(MSBuildSDKsPath)\Microsoft.NET.Sdk.Web\Sdk\Sdk.Props at the beginning.
  • 在结束时从 $(MSBuildSDKsPath)\Microsoft.NET.Sdk.Web\Sdk\Sdk.targets 导入目标文件。Imports the targets file from $(MSBuildSDKsPath)\Microsoft.NET.Sdk.Web\Sdk\Sdk.targets at the end.

MSBuildSDKsPath(装有 Visual Studio 2017 Enterprise)的默认位置是 %programfiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks 文件夹。The default location for MSBuildSDKsPath (with Visual Studio 2017 Enterprise) is the %programfiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks folder.

Microsoft.NET.Sdk.Web SDK 依赖于:The Microsoft.NET.Sdk.Web SDK depends on:

  • Microsoft.NET.Sdk.Web.ProjectSystemMicrosoft.NET.Sdk.Web.ProjectSystem
  • Microsoft.NET.Sdk.PublishMicrosoft.NET.Sdk.Publish

它们会导致导入以下属性和目标:Which causes the following properties and targets to be imported:

  • $(MSBuildSDKsPath)\Microsoft.NET.Sdk.Web.ProjectSystem\Sdk\Sdk.Props$(MSBuildSDKsPath)\Microsoft.NET.Sdk.Web.ProjectSystem\Sdk\Sdk.Props
  • $(MSBuildSDKsPath)\Microsoft.NET.Sdk.Web.ProjectSystem\Sdk\Sdk.targets$(MSBuildSDKsPath)\Microsoft.NET.Sdk.Web.ProjectSystem\Sdk\Sdk.targets
  • $(MSBuildSDKsPath)\Microsoft.NET.Sdk.Publish\Sdk\Sdk.Props$(MSBuildSDKsPath)\Microsoft.NET.Sdk.Publish\Sdk\Sdk.Props
  • $(MSBuildSDKsPath)\Microsoft.NET.Sdk.Publish\Sdk\Sdk.targets$(MSBuildSDKsPath)\Microsoft.NET.Sdk.Publish\Sdk\Sdk.targets

发布目标将根据使用的发布方法,导入正确的目标集。Publish targets import the right 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

加载项目时,将计算项目项(文件)。When the project is loaded, the project items (files) are computed. item type 属性确定如何处理该文件。The item type attribute 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/** 的文件将包含在 Content 项内。By default, files matching the pattern wwwroot/** are included in the Content item. wwwroot/\*\* glob 模式 匹配 wwwroot 文件夹及其子文件夹中的所有文件。The wwwroot/\*\* globbing pattern matches all files in the wwwroot folder and subfolders. 若要将文件显式添加到发布列表,请直接在 .csproj 文件中添加文件,如包含文件中所示。To explicitly add a file to the publish list, add the file directly in the .csproj file as shown in Include Files.

在 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 文件)运行 dotnet publish 命令。In the samples below, the dotnet publish command is run from the project directory (which contains the .csproj file). 如果不在项目文件夹中,则可以在项目文件路径中显式传递。If not in the project folder, 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 output similar to the following:

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

  Web1 -> C:\Webs\Web1\bin\Debug\netcoreapp{X.Y}\Web1.dll
  Web1 -> C:\Webs\Web1\bin\Debug\netcoreapp{X.Y}\publish\

默认发布文件夹为 bin\$(Configuration)\netcoreapp<version>\publishThe default publish folder is bin\$(Configuration)\netcoreapp<version>\publish. $(Configuration) 的默认值为 Debug。The default for $(Configuration) is Debug. 在上述示例中,<TargetFramework>netcoreapp{X.Y}In the preceding sample, the <TargetFramework> is netcoreapp{X.Y}.

dotnet publish -h 显示用于发布的帮助信息。dotnet publish -h displays help information for 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 参数映射到 Configuration MSBuild 属性。The -c parameter maps to the Configuration MSBuild property. -o 参数映射到 OutputPathThe -o parameter maps to OutputPath.

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

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

以下命令将 Release 版本发布到网络共享:The following command publishes a Release build to a network share:

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

网络共享通过正斜杠指定 (//r8/) 并适用于所有支持 .NET Core 的平台。The network share is specified with forward slashes (//r8/) and works on all .NET Core supported platforms.

确认用于部署的发布应用未在运行。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 2017 或更高版本创建发布配置文件。This section uses Visual Studio 2017 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 capacities page is displayed. 如果项目缺少发布配置文件,将显示以下页面:If the project lacks a publish profile, the following page is displayed:

随即显示应用程序容量页的“发布”选项卡

当选择“文件夹”时,指定一个文件夹路径来存储发布的资产。When Folder is selected, specify a folder path to store the published assets. 默认文件夹是 bin\Release\PublishOutput。The default folder is bin\Release\PublishOutput. 单击“创建配置文件”按钮即可完成。Click the Create Profile button to finish.

创建发布配置文件后,“发布”选项卡将更改。Once a publish profile is created, the Publish tab changes. 新创建的配置文件显示在下拉列表中。The newly created profile appears in a drop-down list. 单击“创建新配置文件”以创建其他新配置文件。Click Create new profile to create another new profile.

显示 FolderProfile 的应用程序容量页的“发布”选项卡

发布向导支持以下发布目标:The Publish wizard supports the following publish targets:

  • Azure 应用服务Azure App Service
  • Azure 虚拟机Azure Virtual Machines
  • IIS、FTP 等(适用于任何 Web 服务器)IIS, FTP, etc. (for any web server)
  • 文件夹Folder
  • 导入配置文件Import Profile

有关详细信息,请参阅哪些发布选项适合我For more information, see What publishing options are right for me.

使用 Visual Studio 创建发布配置文件时,将创建 Properties/PublishProfiles/{PROFILE NAME}.pubxml MSBuild 文件。When creating a publish profile with Visual Studio, a Properties/PublishProfiles/{PROFILE NAME}.pubxml MSBuild file is created. 此 .pubxml 文件为 MSBuild 文件,包含发布配置设置。The .pubxml file is a MSBuild file and contains publish configuration settings. 可以更改此文件以自定义生成和发布过程。This file can be changed to customize the build and publish process. 通过发布过程读取此文件。This file is read by the publishing process. <LastUsedBuildConfiguration> 比较特殊,因为它是一个全局属性,不应出现在导入生成的任何文件中。<LastUsedBuildConfiguration> is special because it's a global property and shouldn't be in any file that's imported in the build. 有关详细信息,请参阅 MSBuild:如何设置配置属性See MSBuild: how to set the configuration property for more information.

发布到 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 应用的概述,请参阅托管和部署For an overview of how to publish a web app on ASP.NET Core, see Host and deploy. 发布 ASP.NET Core 应用程序所需的 MSBuild 任务和目标是开放源代码,位于: https://github.com/aspnet/websdk。The MSBuild tasks and targets necessary to publish an ASP.NET Core app are open-source at https://github.com/aspnet/websdk.

dotnet publish 可以使用文件夹、MSDeploy 和 Kudu 发布配置文件:dotnet publish can use folder, MSDeploy, and Kudu publish profiles:

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

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

MSDeploy(当前仅适用于 Windows,因为 MSDeploy 不是跨平台的):MSDeploy (currently this only works in Windows since MSDeploy isn't cross-platform):

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

MSDeploy 包(当前仅适用于 Windows,因为 MSDeploy 不是跨平台的):MSDeploy package (currently this only works in Windows since MSDeploy isn't cross-platform):

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

在前面示例中,不会将 deployonbuild 传递到 dotnet publishIn the preceding samples, 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.

向“属性/发布配置文件”文件夹添加包含以下内容的发布配置文件:Add a publish profile to the 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

调用 dotnet build 时,它调用 msbuild 来运行生成和发布过程。When invoking dotnet build, it calls msbuild to run the build and publish process. 当传递到文件夹配置文件中时,调用 dotnet buildmsbuild 的作用是相同的。Calling either dotnet build or msbuild is 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. MSDeploy 目前仅限于在 Windows 计算机上进行发布。MSDeploy is currently limited to Windows machines for publishing. 在非文件夹配置文件上调用 dotnet build 时,会调用 MSBuild,并且 MSBuild 在非文件夹配置文件上使用 MSDeploy。Calling dotnet build on a non-folder profile invokes MSBuild, and MSBuild uses MSDeploy on non-folder profiles. 在非文件夹配置文件上调用 dotnet build 时,会调用 MSBuild(使用 MSDeploy)并导致失败(即使在 Windows 平台上运行也是如此)。Calling dotnet build on a non-folder profile invokes MSBuild (using MSDeploy) and results in a failure (even when running on a Windows platform). 若要使用非文件夹配置文件进行发布,请直接调用 MSBuild。To 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>

请注意,<LastUsedBuildConfiguration> 已设置为 ReleaseNote <LastUsedBuildConfiguration> is set to Release. 从 Visual Studio 发布时,在启动发布过程后将使用该值设置 <LastUsedBuildConfiguration> 配置属性值。When publishing from Visual Studio, the <LastUsedBuildConfiguration> configuration property value is set using the value when the publish process is started. <LastUsedBuildConfiguration> 配置属性比较特殊,不应在导入的 MSBuild 文件中覆盖该属性。The <LastUsedBuildConfiguration> configuration property is special and shouldn't be overridden in an imported MSBuild file. 可以从命令行覆盖此属性。This property can be overridden from the command line.

使用 .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

从命令行发布到 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 dotnet msbuild command from a Windows command prompt:

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 available cross-platform 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 endpoint. MSDeploy 仅在 Windows 上可用。MSDeploy is only available on Windows.

设置环境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 应用时,生成项目和 wwwroot 文件夹的内容包括在内。When publishing ASP.NET Core web apps, the build artifacts and contents of the wwwroot folder are included. msbuild 支持通配模式msbuild supports globbing patterns. 例如,以下 <Content> 元素将从 wwwroot/content 文件夹及其所有子文件夹中排除所有文本 (.txt) 文件。For example, the following <Content> element excludes all text (.txt) files from the wwwroot/content folder and all 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 the following output:

MSDeployPublish:
  Starting Web deployment task from source: manifest(C:\Webs\Web1\obj\Release\netcoreapp1.1\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

以下标记将项目目录外的 images 文件夹包含到发布站点的 wwwroot/images 文件夹中:The following markup includes an images folder outside the project directory to the wwwroot/images folder of the publish site:

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

可以将标记添加到 .csproj 文件或发布配置文件。The markup 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.

以下突出显示的标记显示如何:The following highlighted markup shows how to:

  • 将文件从项目外部复制到 wwwroot 文件夹。Copy a file from outside the project into the wwwroot folder.
  • 排除 wwwroot\Content 文件夹。Exclude the wwwroot\Content folder.
  • 排除 Views\Home\About2.cshtml。Exclude Views\Home\About2.cshtml.
<?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 />
    <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>

请参阅 WebSDK 自述文件,了解更多部署示例。See the WebSDK Readme for more deployment samples.

在发布前或发布后运行目标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