Inicio rápido: Crear y publicar un paquete (CLI de dotnet)Quickstart: Create and publish a package (dotnet CLI)

La creación de un paquete NuGet desde una biblioteca de clases de .NET y su publicación en nuget.org con la interfaz de la línea de comandos (CLI) de dotnet es un proceso simple.It's a simple process to create a NuGet package from a .NET Class Library and publish it to nuget.org using the dotnet command-line interface (CLI).

Requisitos previosPrerequisites

  1. Instalar el SDK de .NET Core, que incluye la CLI de dotnet.Install the .NET Core SDK, which includes the dotnet CLI.

  2. Registrar una cuenta gratuita en nuget.org si aún no tiene uno.Register for a free account on nuget.org if you don't have one already. Al crear una cuenta se envía un correo electrónico de confirmación.Creating a new account sends a confirmation email. Debe confirmar la cuenta para poder cargar un paquete.You must confirm the account before you can upload a package.

Crear un proyecto de biblioteca de clasesCreate a class library project

Puede usar un proyecto de biblioteca de clases .NET existente para el código que desea empaquetar o crear uno simple tal y como se indica a continuación:You can use an existing .NET Class Library project for the code you want to package, or create a simple one as follows:

  1. Cree una carpeta denominada AppLogger y vaya a ella.Create a folder called AppLogger and change into it.

  2. Cree el proyecto con dotnet new classlib, que utiliza el nombre de la carpeta actual para el proyecto.Create the project using dotnet new classlib, which uses the name of the current folder for the project.

Agregar metadatos de paquete al archivo de proyectoAdd package metadata to the project file

Cada paquete NuGet necesita un manifiesto que describa su contenido y sus dependencias.Every NuGet package needs a manifest that describes the package's contents and dependencies. En un paquete final, el manifiesto es un archivo .nuspec que se genera a partir de las propiedades de metadatos de NuGet que se incluyen en el archivo de proyecto.In a final package, the manifest is a .nuspec file that is generated from the NuGet metadata properties that you include in the project file.

  1. Abra el archivo de proyecto (.csproj) y agregue las siguientes propiedades mínimas dentro de la etiqueta <PropertyGroup> de salida, cambiando los valores según corresponda:Open your project file (.csproj) and add the following minimal properties inside the exiting <PropertyGroup> tag, changing the values as appropriate:

    <PackageId>AppLogger</PackageId>
    <Version>1.0.0</Version>
    <Authors>your_name</Authors>
    <Company>your_company</Company>
    

    Importante

    Asigne al paquete un identificador que sea único en nuget.org o en el host que use.Give the package an identifier that's unique across nuget.org or whatever host you're using. En este tutorial, se recomienda incluir "muestra" o "prueba" en el nombre porque el paso de publicación posterior hace que el paquete sea visible públicamente (aunque no es probable que nadie lo use realmente).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).

  2. Agregue las propiedades opcionales que se describen en Propiedades de metadatos de NuGet.Add any optional properties described on NuGet metadata properties.

    Nota

    En el caso de los paquetes creados para consumo público, preste especial atención la propiedad PackageTags, dado que estas etiquetas ayudan a otros usuarios a encontrar el paquete y comprender lo que hace.For packages built for public consumption, pay special attention to the PackageTags property, as tags help others find your package and understand what it does.

Ejecutar el comando packRun the pack command

Para compilar un paquete NuGet (un archivo .nupkg) desde el proyecto, ejecute el comando dotnet pack, que también genera el proyecto automáticamente:To build a NuGet package (a .nupkg file) from the project, run the dotnet pack command, which also builds the project automatically:

# Uses the project file in the current folder by default
dotnet pack

El resultado mostrará la ruta de acceso al archivo .nupkg:The output shows the path to the .nupkg file:

Microsoft (R) Build Engine version 15.5.180.51428 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  Restore completed in 29.91 ms for D:\proj\AppLoggerNet\AppLogger\AppLogger.csproj.
  AppLogger -> D:\proj\AppLoggerNet\AppLogger\bin\Debug\netstandard2.0\AppLogger.dll
  Successfully created package 'D:\proj\AppLoggerNet\AppLogger\bin\Debug\AppLogger.1.0.0.nupkg'.

Generación automática del paquete en la compilaciónAutomatically generate package on build

Para ejecutar automáticamente dotnet pack al ejecutar dotnet build, agregue la siguiente línea al archivo de proyecto en <PropertyGroup>:To automatically run dotnet pack when you run dotnet build, add the following line to your project file within <PropertyGroup>:

<GeneratePackageOnBuild>true</GeneratePackageOnBuild>

Publicar el paquetePublish the package

Cuando tenga un archivo .nupkg, publíquelo en nuget.org con el comando dotnet nuget push y una clave de API adquirida de nuget.org.Once you have a .nupkg file, you publish it to nuget.org using the dotnet nuget push command along with an API key acquired from nuget.org.

Nota

Virus scanning: All packages uploaded to nuget.org are scanned for viruses and rejected if any viruses are found. All packages listed on nuget.org are also scanned periodically.

Packages published to nuget.org are also publicly visible to other developers unless you unlist them. To host packages privately, see Hosting packages.

Adquirir la clave de APIAcquire your API key

  1. Sign into your nuget.org account or create an account if you don't have one already.

  2. 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. Under API Key, enter * for Glob pattern, then select Create. (See below for more about scopes.)

  4. Once the key is created, select Copy to retrieve the access key you need in the CLI:

    Copying the API key to the clipboard

  5. Important: Save your key in a secure location because you cannot copy the key again later on. If you return to the API key page, you need to regenerate the key to copy it. You can also remove the API key if you no longer want to push packages via the CLI.

Scoping allows you to create separate API keys for different purposes. 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. 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. For more information, see Introducing scoped API keys (blogs.nuget.org).

Publicar con dotnet nuget pushPublish with dotnet nuget push

  1. Change to the folder containing the .nupkg file.

  2. Run the following command, specifying your package name 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 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.
    

See dotnet nuget push.

Errores de publicaciónPublish errors

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. The name "AppLogger", for example, already exists. 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.).

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. Change the package identifier, rebuild the project, recreate the .nupkg file, and retry the push command.

Administrar el paquete publicadoManage the published package

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:

This package has not been indexed yet. It will appear in search results and will be available for install/restore after indexing is complete.

And that's it! 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. 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:

    Trash can icon shown for a package listing on nuget.org

  3. On the subsequent page, clear the box labeled List (package-name) in search results and select Save:

    Clearing the List checkbox for a package on nuget.org