Visual Studio 發佈設定檔 (. .pubxml) 以進行 ASP.NET Core 應用程式部署Visual Studio publish profiles (.pubxml) 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\** 萬用字元模式會比對 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. 在下列範例中,.NET Core CLI 的 dotnet publish 命令是從專案目錄執行 (此目錄包含 .csproj 檔案)。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 App ServiceAzure App Service
  • Linux 上的 Azure App ServiceAzure App Service on Linux
  • Azure 虛擬機器Azure Virtual Machines
  • 資料夾Folder
  • IIS、FTP、Web Deploy (適用於任何網頁伺服器)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/{設定檔名稱}.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 工作和目標是 dotnet/websdk 存放庫中的開放原始碼。The MSBuild tasks and targets necessary to publish an ASP.NET Core web app are open-source in the dotnet/websdk repository.

下列命令可以使用資料夾、Msdeploy.exe 和 Kudu 發行設定檔。The following commands 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>
dotnet build WebApplication.csproj /p:DeployOnBuild=true /p:PublishProfile=<FolderProfileName>

MSDeploy:MSDeploy:

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

MSDeploy 套件:MSDeploy package:

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

在上述範例中:In the preceding examples:

  • dotnet publishdotnet build 支援從任何平臺發佈至 Azure 的 Kudu api。dotnet publish and dotnet build support 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.
  • 請勿傳遞 DeployOnBuilddotnet publish 命令。Don't pass DeployOnBuild to the dotnet publish command.

如需詳細資訊,請參閱Microsoft. Sdk。For more information, see Microsoft.NET.Sdk.Publish.

將含有下列內容的發行設定檔新增至專案的 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>

資料夾發佈範例Folder publish example

使用名為 FolderProfile 的設定檔發佈時,請使用下列任何一個命令:When publishing with a profile named FolderProfile, use any of the following commands:

dotnet publish /p:Configuration=Release /p:PublishProfile=FolderProfile
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 時,會使用 .NET Framework 版本的 MSBuild。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. 即使專案根目錄中有 App_Data 資料夾,<ExcludeApp_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 publish /p:Configuration=Release /p:PublishProfile=FolderProfile
      
      dotnet build -c Release /p:DeployOnBuild=true /p:PublishProfile=FolderProfile
      
    • 使用 MSBuild:Using MSBuild:

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

    如需詳細資訊,請參閱 MSBuild: how to set the configuration property (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 應用程式,名為 AzureWebAppThe 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.exe 使用者名稱。{USERNAME}: MSDeploy username. {USERNAME}可以在發行設定檔中找到。The {USERNAME} can be found in the publish profile.
  • {PASSWORD}: Msdeploy.exe 密碼。{PASSWORD}: MSDeploy password. {PASSWORD}{PROFILE} 取得。.Publishsettings 檔案。Obtain the {PASSWORD} from the {PROFILE}.PublishSettings file. 從下列其中一個位置下載 .PublishSettings 檔案:Download the .PublishSettings file from either:
    • 方案總管:選取 View > Cloud ExplorerSolution 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 Deploy 的發行設定檔: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

在發行設定檔 (.pubxml) 或專案檔中包括 <EnvironmentName> 屬性,以設定應用程式的 環境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
  • 符合下列萬用字元模式的資料夾和檔案: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 支援萬用字元模式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 檔案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 屬性萬用字元模式的檔案。Declares a _CustomFiles item to store files matching the Include attribute's globbing pattern. 模式中參考的 images 資料夾位於專案目錄外。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.cshtmlExcluding 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 README file.

在發佈之前或之後執行目標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

<AllowUntrustedCertificate> 屬性搭配 True 值新增至發行設定檔:Add the <AllowUntrustedCertificate> property with a value of True to the publish profile:

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

Kudu 服務The Kudu service

若要檢視 Azure App Service 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