This post is about how to Create and Publish a NuGet Package with dotnet CLI. We will also look into how to publish the nuget package to nuget.org.
First we need to create a nuget package. To create nuget package, we need to create a class library. I am using the dotnet new classlib -o Device.Detection --framework net6.0. I am building this nuget package which will help us to identify whether request is coming from a mobile device or not. I am using code from https://stackoverflow.com/a/68641796/38024. Here is the extension method I created.
We need to add reference of Microsoft.AspNetCore.Http.Abstractions nuget package. For setting the nuget package properties we need to modify project file. Here is the modified project file.
To build the nuget package, either we can use the dotnet build command since we added the GeneratePackageOnBuild element - it build nuget package as well or we can use the dotnet pack build.
Once it is build we can push the nuget package to nuget.org using the dotnet nuget push command. To use the dotnet nuget push command, we need an API key from nuget.org. First we need to create an account in nuget.org then we need to create an API key. I already created an API Key.
Then we can run the command dotnet nuget push DotNetThoughts.Device.Detection.1.0.0.nupkg --api-key $env:NuGetKey --source https://api.nuget.org/v3/index.json
This way we can create and publish nuget package. Next we can create a GitHub action which will create and publish nuget packages. Here is the GitHub action YAML code.
Since we need to use the API Key in GitHub Action, we need to create a GitHub Action secret - NUGET_KEY and use the value from nuget.org. Here is the action running.
This way we can publish a nuget package to nuget.org. When ever we change something it will trigger the build and deploy the nuget package to nuget.org.