Publishing a NuGet package to GitHub Packages

Posted by

GitHub Packages is a similar artifact management system to NuGet, Artifactory, and Azure Artifacts. Using it to publish .NET packages wasn’t as straight forward as I hoped, but I’ve clearly documented my steps below:

We started with a blank repository and demo .NET project. Next:

1. Add reference in the project file to the repository where we will publish the packages to. Editing our project file, we added this line on line 5. Note the account and repository name that we are using.

<RepositoryUrl>https://github.com/samsmithnz/GHPackages</RepositoryUrl>

2. Next we are going to create an action to build and deploy. First step in the action is to pack the package with dotnet. Using “dotnet pack“, with the project name and configuration, we create the NuGet package

- name: Pack
  run: dotnet pack DemoLibrary/DemoLibrary/DemoLibrary.csproj -c Release

3. Next we prep the hosted agent, adding the destination package. In the code below, using “dotnet nuget add source“, we use the github account and password (using the built in GITHUB_TOKEN), to setup the package registry for my account.

- name: Prep packages
  run: dotnet nuget add source --username samsmithnz --password ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text --name github "https://nuget.pkg.github.com/samsmithnz/index.json"

4. Finally, we publish the package to GitHub packages. Using “dotnet nuget push“, with the NuGet package location, defaulting the api-key to GITHUB_TOKEN again, and specifying the source “github” (that we just setup in step 3).

- name: Publish to GitHub packages 
  run: dotnet nuget push DemoLibrary/DemoLibrary/bin/Release/*.nupkg --api-key ${{ secrets.GITHUB_TOKEN }}  --source "github"

The action runs successfully (after some tweaks), and now we can see the package on the home page of the repo, on the right.

When to use a PAT token or GITHUB_TOKEN

Note that if you need to install packages from other private repositories, you need to use a PAT token instead of the GitHub Token. This is documented in detail in this reference, but is essentially the same as what we’ve worked through – replacing the GitHub token with the PAT token.

Wrap up

Today we learned how to publish a NuGet package to GitHub Packages.

References

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s