快速入門:使用 Visual Studio 建立及發行 NuGet 套件 (.NET Standard,僅限 Windows)Quickstart: Create and publish a NuGet package using Visual Studio (.NET Standard, Windows only)

使用 CLI 工具可以輕鬆在 Windows 上從 Visual Studio 中的 .NET Standard 類別庫建立 NuGet 套件,然後將其發行到 nuget.org。It's a simple process to create a NuGet package from a .NET Standard Class Library in Visual Studio on Windows, and then publish it to nuget.org using a CLI tool.

注意

若您是使用 Visual Studio for Mac,請參閱此資訊以了解如何建立 NuGet 套件,或使用 dotnet CLI 工具來建立套件。If you are using Visual Studio for Mac, refer to this information on creating a NuGet package, or use the dotnet CLI tools.

必要條件Prerequisites

  1. 使用 .NET Core 相關工作負載,從 visualstudio.com 安裝任何版本的 Visual Studio 2019。Install any edition of Visual Studio 2019 from visualstudio.com with a .NET Core related workload.

  2. 安裝 dotnet CLI (若尚未安裝)。If it's not already installed, install the dotnet CLI.

    針對 dotnet CLI,從 Visual Studio 2017 開始,dotnet CLI 會自動與任何 .NET Core 相關工作負載一起安裝。For the dotnet CLI, starting in Visual Studio 2017, the dotnet CLI is automatically installed with any .NET Core related workloads. 否則,請安裝 .NET Core SDK 以取得 dotnet CLI。Otherwise, install the .NET Core SDK to get the dotnet CLI. 使用 dotnetSDK 樣式格式 (SDK 屬性) 的 .NET Standard 專案需要 CLI。The dotnet CLI is required for .NET Standard projects that use the SDK-style format (SDK attribute). 此文章中使用的 Visual Studio 2017 與更高版本中的預設 .NET Standard 類別庫範本使用 SDK 屬性。The default .NET Standard class library template in Visual Studio 2017 and higher, which is used in this article, uses the SDK attribute.

    重要

    若您正在處理非 SDK 樣式專案,請改為依照建立及發行 .NET Framework 套件 (Visual Studio) 中的程序建立及發行套件。If you are working with a non-SDK-style project, follow the procedures in Create and publish a .NET Framework package (Visual Studio) to create and publish the package instead. 針對此文章,建議使用 dotnet CLI。For this article, the dotnet CLI is recommended. 雖然您可以使用 nuget.exe CLI 發行任何 NuGet 套件,此文章中的某些步驟僅適用於 SDK 專案與 dotnet CLI。Although you can publish any NuGet package using the nuget.exe CLI, some of the steps in this article are specific to SDK-style projects and the dotnet CLI. nuget.exe CLI 是用於非 SDK 樣式專案 (通常是 .NET Framework)。The nuget.exe CLI is used for non-SDK-style projects (typically .NET Framework).

  3. 如果您還沒有帳戶,請在 nuget.org 上註冊一個免費帳戶 (英文)。Register for a free account on nuget.org if you don't have one already. 建立新的帳戶會傳送一封確認電子郵件。Creating a new account sends a confirmation email. 您必須確認帳戶,才可以上傳套件。You must confirm the account before you can upload a package.

建立類別庫專案Create a class library project

您可以針對要封裝的程式碼使用現有的 .NET Standard 類別庫專案,或建立一個簡單的專案,如下所示:You can use an existing .NET Standard Class Library project for the code you want to package, or create a simple one as follows:

  1. 在 Visual Studio 中,選擇 [檔案] > [新增] > [專案]、展開 [Visual C#] > [.NET Standard] 節點、選取 [類別庫 (.NET Standard)] 範本、將專案命名為 AppLogger,然後按一下 [確定]。In Visual Studio, choose File > New > Project, expand the Visual C# > .NET Standard node, select the "Class Library (.NET Standard)" template, name the project AppLogger, and click OK.

    提示

    除非您有理由選擇,否則 .NET Standard 是 NuGet 套件的慣用目標,因為它能與範圍最廣泛的取用專案相容。Unless you have a reason to choose otherwise, .NET Standard is the preferred target for NuGet packages, as it provides compatibility with the widest range of consuming projects.

  2. 在產生的專案檔上按一下滑鼠右鍵,然後選取 [建置] 以確定已適當建立專案。Right-click on the resulting project file and select Build to make sure the project was created properly. DLL 位於 Debug 資料夾 (如果您改為建置該組態則為 Release)。The DLL is found within the Debug folder (or Release if you build that configuration instead).

當然,在真實的 NuGet 套件中,您會實作其他人可以用來建置應用程式的許多實用功能。Within a real NuGet package, of course, you implement many useful features with which others can build applications. 不過,對於此逐步解說,您將不會撰寫任何額外的程式碼,因為來自範本的類別庫已足夠建立套件。For this walkthrough, however, you won't write any additional code because a class library from the template is sufficient to create a package. 不過,如果您想要為套件新增一些函式程式碼,可以使用下列方式:Still, if you'd like some functional code for the package, use the following:

namespace AppLogger
{
    public class Logger
    {
        public void Log(string text)
        {
            Console.WriteLine(text);
        }
    }
}

設定套件屬性Configure package properties

  1. 以滑鼠右鍵按一下 [方案總管] 中的專案,然後選擇 [屬性] 功能表命令,然後選取 [套件] 索引標籤。Right-click the project in Solution Explorer, and choose Properties menu command, then select the Package tab.

    [套件] 索引標籤只會針對 Visual Studio 中的 SDK 樣式專案 (通常是 .NET Standard 或 .NET Core 類別庫專案) 顯示;若您是以非 SDK 樣式專案 (通常是 .NET Framework) 為目標,請移轉專案或改為參閱建立及發行 .NET Framework 套件以取得逐步指示。The Package tab appears only for SDK-style projects in Visual Studio, typically .NET Standard or .NET Core class library projects; if you are targeting a non-SDK style project (typically .NET Framework), either migrate the project or see Create and publish a .NET Framework package instead for step-by-step instructions.

    Visual Studio 專案中的 NuGet 套件屬性

    注意

    針對公眾取用而建置的套件,請特別注意 Tags 屬性,因為標籤可協助其他人找到您的套件,並了解其用途。For packages built for public consumption, pay special attention to the Tags property, as tags help others find your package and understand what it does.

  2. 為套件指定唯一識別碼,並填入任何其他所需的屬性。Give your package a unique identifier and fill out any other desired properties. 針對將 MSBuild 屬性 (SDK 樣式專案) 對應到 .nuspec 中的屬性,請參閱封裝目標For a mapping of MSBuild properties (SDK-style project) to properties in a .nuspec, see pack targets. 如需有關屬性的說明, 請參閱 .nuspec 檔案參考For descriptions of properties, see the .nuspec file reference. 此處的所有屬性都會移入 Visual Studio 針對專案建立的 .nuspec 資訊清單。All of the properties here go into the .nuspec manifest that Visual Studio creates for the project.

    重要

    您必須為套件指定識別碼,此識別碼在 nuget.org 上或您使用的任何主機上都必須是唯一的。You must give the package an identifier that's unique across nuget.org or whatever host you're using. 針對此逐步解說,我們建議在名稱中包含 "Sample" 或 "Test" (如同稍後發行步驟所做的),讓套件能夠成為公開可見的 (儘管實際上不太可能會有人使用它)。For this walkthrough we recommend including "Sample" or "Test" in the name as the later publishing step does make the package publicly visible (though it's unlikely anyone will actually use it).

    如果您嘗試發行名稱已經存在的套件,則會看到錯誤。If you attempt to publish a package with a name that already exists, you see an error.

  3. (選擇性) 若要直接查看專案檔中的屬性,請以滑鼠右鍵按一下 [方案總管] 中的專案,並選取 [編輯 AppLogger.csproj]。(Optional) To see the properties directly in the project file, right-click the project in Solution Explorer and select Edit AppLogger.csproj.

    只有使用 SDK 樣式屬性的專案 (且必須使用 Visual Studio 2017 與更新版本) 才能使用此選項。This option is only available starting in Visual Studio 2017 for projects that use the SDK-style attribute. 否則,以滑鼠右鍵按一下專案並選擇 [卸載專案]。Otherwise, right-click the project and choose Unload Project. 接著,以滑鼠右鍵按一下卸載的專案並選擇 [編輯 AppLogger.csproj]。Then right-click the unloaded project and choose Edit AppLogger.csproj.

執行 pack 命令Run the pack command

  1. 設定要發行的組態。Set the configuration to Release.

  2. 在 [方案總管] 中,以滑鼠右鍵按一下專案,然後選取 [封裝] 命令:Right click the project in Solution Explorer and select the Pack command:

    Visual Studio 專案捷徑功能表上的 NuGet 封裝命令

    若您沒有看到 Pack 命令,您的專案可能並不是 SDK 樣式專案,且您必須使用 nuget.exe CLI。If you don't see the Pack command, your project is probably not an SDK-style project and you need to use the nuget.exe CLI. 移轉專案 並使用 dotnet CLI,或改為參閱建立及發行 .NET Framework 套件以取得逐步指示。Either migrate the project and use dotnet CLI, or see Create and publish a .NET Framework package instead for step-by-step instructions.

  3. Visual Studio 會建置專案並建立 .nupkg 檔案。Visual Studio builds the project and creates the .nupkg file. 檢查 [輸出] 視窗以取得詳細資料 (如下所示),其中包含套件檔案的路徑。Examine the Output window for details (similar to the following), which contains the path to the package file. 另請注意,建置的組建是位於 bin\Release\netstandard2.0,以適用 .NET Standard 2.0 目標。Note also that the built assembly is in bin\Release\netstandard2.0 as befits the .NET Standard 2.0 target.

    1>------ Build started: Project: AppLogger, Configuration: Release Any CPU ------
    1>AppLogger -> d:\proj\AppLogger\AppLogger\bin\Release\netstandard2.0\AppLogger.dll
    1>Successfully created package 'd:\proj\AppLogger\AppLogger\bin\Release\AppLogger.1.0.0.nupkg'.
    ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
    

(選擇性) 建置時產生套件(Optional) Generate package on build

您可以設定 Visual Studio,在建置專案時自動產生 NuGet 套件。You can configure Visual Studio to automatically generate the NuGet package when you build the project.

  1. 在 [方案總管] 中,以滑鼠右鍵按一下專案,然後選擇 [屬性]。In Solution Explorer, right-click the project and choose Properties.

  2. 在 [套件] 索引標籤中,選取 [在建置時產生 NuGet 套件]。In the Package tab, select Generate NuGet package on build.

    建置時自動產生套件

注意

當您自動產生套件時,封裝的時間會增加專案的建置時間。When you automatically generate the package, the time to pack increases the build time for your project.

(選擇性) 使用 MSBuild 進行封裝(Optional) pack with MSBuild

當專案包含必要的套件資料時,NuGet 4.x+ 和 MSBuild 15.1+ 可支援 目標,而這是使用 [封裝] pack 功能表命令的另一種替代方法。As an alternate to using the Pack menu command, NuGet 4.x+ and MSBuild 15.1+ supports a pack target when the project contains the necessary package data. 請開啟命令提示字元,巡覽至專案資料夾並執行下列命令。Open a command prompt, navigate to your project folder and run the following command. (若從 [開始] 功能表啟動 [適用於 Visual Studio 的開發人員命令提示字元],其中就會設定好 MSBuild 的所有必要路徑,因此這是建議的做法。)(You typically want to start the "Developer Command Prompt for Visual Studio" from the Start menu, as it will be configured with all the necessary paths for MSBuild.)

如需詳細資訊,請參閱使用 MSBuild 建立套件For more information, see Create a package using MSBuild.

發行套件Publish the package

一旦擁有 .nupkg 檔案之後,您會使用 nuget.exe CLI 或 dotnet.exe CLI 以及從 nuget.org 取得的 API 金鑰,將它發行到 nuget.org。Once you have a .nupkg file, you publish it to nuget.org using either the nuget.exe CLI or the dotnet.exe CLI along with an API key acquired from nuget.org.

注意

病毒掃描:會掃描所有上傳至 nuget.org 的套件是否有病毒,並在發現任何病毒時予以拒絕。Virus scanning: All packages uploaded to nuget.org are scanned for viruses and rejected if any viruses are found. 也會定期掃描 nuget.org 上列出的所有套件。All packages listed on nuget.org are also scanned periodically.

除非您取消列出已發行至 nuget.org 的套件,否則也會向其他開發人員公開顯示這些套件。Packages published to nuget.org are also publicly visible to other developers unless you unlist them. 若要私下裝載套件,請參閱裝載套件To host packages privately, see Hosting packages.

取得 API 金鑰Acquire your API key

  1. 登入 nuget.org 帳戶 (英文),或者,如果您還沒有帳戶,則建立一個帳戶。Sign into your nuget.org account or create an account if you don't have one already.

    如需有關建立帳戶的詳細資訊,請參閱個人帳戶For more information on creating your account, see Individual accounts.

  2. 選取您的使用者名稱 (在右上方),然後選取 [API 金鑰] 。Select your user name (on the upper right), then select API Keys.

  3. 選取 [建立] ,提供金鑰的名稱,選取 [選取範圍] > [推送] 。Select Create, provide a name for your key, select Select Scopes > Push. 針對 [Glob 模式] 輸入 *,然後選取 [建立] 。Enter * for Glob pattern, then select Create. (如需範圍的詳細資訊,請參閱下方)。(See below for more about scopes.)

  4. 建立金鑰之後,選取 [複製] 以擷取 CLI 中您需要的存取金鑰:Once the key is created, select Copy to retrieve the access key you need in the CLI:

    將 API 金鑰複製到剪貼簿

  5. 重要:將您的金鑰儲存在安全的位置,因為您稍後就無法再次複製此金鑰。Important: Save your key in a secure location because you cannot copy the key again later on. 如果您返回 API 金鑰頁面,則需要重新產生金鑰才能加以複製。If you return to the API key page, you need to regenerate the key to copy it. 如果您不再想要透過 CLI 推送套件,也可以移除 API 金鑰。You can also remove the API key if you no longer want to push packages via the CLI.

設定範圍可讓您針對不同用途建立個別的 API 金鑰。Scoping allows you to create separate API keys for different purposes. 每個金鑰都有其到期的時間範圍,且可將範圍設定為特定套件 (或 Glob 模式)。Each key has its expiration timeframe and can be scoped to specific packages (or glob patterns). 每個金鑰也可將範圍設定為特定作業:新套件和更新的推送、僅更新的推送,或取消列入。Each key is also scoped to specific operations: push of new packages and updates, push of updates only, or delisting. 透過設定範圍,您就可針對組織中管理套件的不同人員建立 API 金鑰,讓他們只具有所需的權限。Through scoping, you can create API keys for different people who manage packages for your organization such that they have only the permissions they need. 如需詳細資訊,請參閱限定範圍的 API 金鑰For more information, see scoped API keys.

使用 dotnet CLI 或 nuget.exe CLI 發佈Publish with the dotnet CLI or nuget.exe CLI

選取您 CLI 工具的索引標籤,它可能是 .NET Core CLI (dotnet CLI) 或 NuGet (nuget.exe CLI)。Select the tab for your CLI tool, either .NET Core CLI (dotnet CLI) or NuGet (nuget.exe CLI).

此步驟是建議用於取代 nuget.exe的步驟。This step is the recommended alternative to using nuget.exe.

您必須先開啟命令列,才能發行套件。Before you can publish the package, you must first open a command line.

  1. 變更為包含 .nupkg 檔案的資料夾。Change to the folder containing the .nupkg file.

  2. 執行下列命令,指定套件名稱 (使用套件識別碼) 並使用您的 API 金鑰來取代金鑰值:Run the following command, specifying your package name (unique package ID) and replacing the key value with your API key:

    dotnet nuget push AppLogger.1.0.0.nupkg -k qz2jga8pl3dvn2akksyquwcs9ygggg4exypy3bhxy6w6x6 -s https://api.nuget.org/v3/index.json
    
  3. dotnet 會顯示發行程序的結果:dotnet displays the results of the publishing process:

    info : Pushing AppLogger.1.0.0.nupkg to 'https://www.nuget.org/api/v2/package'...
    info :   PUT https://www.nuget.org/api/v2/package/
    info :   Created https://www.nuget.org/api/v2/package/ 12620ms
    info : Your package was pushed.
    

請參閱 dotnet nuget pushSee dotnet nuget push.

發行錯誤Publish errors

來自 push 命令的錯誤通常代表發生問題。Errors from the push command typically indicate the problem. 例如,您可能忘記更新專案中的版本號碼,因而嘗試發行已經存在的套件。For example, you may have forgotten to update the version number in your project and are therefore trying to publish a package that already exists.

當您嘗試使用主機上已經存在的識別碼來發行套件時,也會看到錯誤。You also see errors when trying to publish a package using an identifier that already exists on the host. 例如,名稱 "AppLogger" 已經存在。The name "AppLogger", for example, already exists. 在這種情況下,push 命令會產生下列錯誤:In such a case, the push command gives the following error:

Response status code does not indicate success: 403 (The specified API key is invalid,
has expired, or does not have permission to access the specified package.).

如果您使用剛建立的有效 API 金鑰,則此訊息表示命名衝突,這無法從錯誤的「權限」部分中完全清除。If you're using a valid API key that you just created, then this message indicates a naming conflict, which isn't entirely clear from the "permission" part of the error. 請變更套件識別碼、重新建置專案、重新建立 .nupkg 檔案,然後重試 push 命令。Change the package identifier, rebuild the project, recreate the .nupkg file, and retry the push command.

管理已發行的套件Manage the published package

從您在 nuget.org 上的設定檔,選取 [管理套件] 以查看您剛發行的套件。From your profile on nuget.org, select Manage Packages to see the one you just published. 您也會收到確認電子郵件。You also receive a confirmation email. 請注意,可能需要一些時間才會編製套件的索引,並顯示在其他人可以找到它的搜尋結果中。Note that it might take a while for your package to be indexed and appear in search results where others can find it. 在這段期間,套件頁面會顯示下列訊息:During that time your package page shows the message below:

此套件尚未編製索引。

就是這麼容易!And that's it! 您剛剛已將第一個 NuGet 套件發行至 nuget.org,其他開發人員可以在他們自己的專案中使用它。You've just published your first NuGet package to nuget.org that other developers can use in their own projects.

如果您在本逐步解說中建立的套件不是真的很實用 (例如,使用空類別庫建立的套件),則您應該「取消列出」該套件,以便在搜尋結果中加以隱藏:If in this walkthrough you created a package that isn't actually useful (such as a package created with an empty class library), you should unlist the package to hide it from search results:

  1. 在 nuget.org,選取您的使用者名稱 (頁面右上方),然後選取 [管理套件]。On nuget.org, select your user name (upper right of the page), then select Manage Packages.

  2. 在 [已發行] 下方找出您想要取消列出的套件,然後選取右邊的資源回收筒圖示:Locate the package you want to unlist under Published and select the trash can icon on the right:

    針對 nuget.org 上列出之套件顯示的資源回收筒圖示

  3. 在後續頁面上,清除標籤為 [在搜尋結果中列出 (package-name)] 的方塊,然後選取 [儲存]:On the subsequent page, clear the box labeled List (package-name) in search results and select Save:

    針對 nuget.org 上的套件清除 [列出] 核取方塊

新增讀我檔案和其他檔案Adding a readme and other files

若要直接指定套件中要包含的檔案,請編輯專案檔並使用 content 屬性:To directly specify files to include in the package, edit the project file and use the content property:

<ItemGroup>
  <Content Include="readme.txt">
    <Pack>true</Pack>
    <PackagePath>\</PackagePath>
  </Content>
</ItemGroup>

這會在套件根目錄中包含名稱為 readme.txt 的檔案。This will include a file named readme.txt in the package root. Visual Studio 會在直接安裝套件之後,立即以純文字顯示該檔案的內容。Visual Studio displays the contents of that file as plain text immediately after installing the package directly. (不會針對安裝為相依性的套件顯示讀我檔案)。(Readme files are not displayed for packages installed as dependencies). 例如,以下是 HtmlAgilityPack 套件的讀我檔案顯示方式:For example, here's how the readme for the HtmlAgilityPack package appears:

安裝時 NuGet 套件的讀我檔案顯示

注意

只在專案根目錄新增 readme.txt,並不會導致其包含在產生的套件中。Merely adding the readme.txt at the project root will not result in it being included in the resulting package.

Channel 9YouTube上尋找更多 NuGet 影片。Find more NuGet videos on Channel 9 and YouTube.