Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dotnet nuget push to GPR -- Invalid or unrecognized response #8580

Closed
jwillmer opened this issue Sep 12, 2019 · 87 comments
Closed

dotnet nuget push to GPR -- Invalid or unrecognized response #8580

jwillmer opened this issue Sep 12, 2019 · 87 comments
Labels
Functionality:Push Resolution:Question This issues appears to be a question, not a product defect

Comments

@jwillmer
Copy link

I run the following script in GitHub Actions:

      - name: Publish Nuget to GitHub registry
        run: dotnet nuget push ./MyNugetPackage.3.4.24.nupk -s https://nuget.pkg.github.com/USERNAME/index.json -k ${GITHUB_TOKEN}  
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

and I get the following output:


Run nuget push ./MyNugetPackage.3.4.24.nupk -Source https://nuget.pkg.github.com/USERNAME/index.json
Pushing MyNugetPackage.3.4.24.3.4.24.nupkg to 'https://nuget.pkg.github.com/USERNAME'...
  PUT https://nuget.pkg.github.com/USERNAME/
An error was encountered when fetching 'PUT https://nuget.pkg.github.com/USERNAME/'. The request will now be retried.
An error occurred while sending the request.
  The server returned an invalid or unrecognized response.
  PUT https://nuget.pkg.github.com/USERNAME/
An error was encountered when fetching 'PUT https://nuget.pkg.github.com/USERNAME/'. The request will now be retried.
An error occurred while sending the request.
  The server returned an invalid or unrecognized response.
  PUT https://nuget.pkg.github.com/USERNAME/
An error occurred while sending the request.
  The server returned an invalid or unrecognized response.
##[error]Process completed with exit code 1.

I'm running my code inside of ubuntu-latest (18.04) that has the following versions installed: software-in-virtual-environments-for-github-actions

Can someone help me explain what this error means? I don't know how to solve this.

@rrelyea
Copy link
Contributor

rrelyea commented Sep 16, 2019

@anangaur - has your experience with GPR given you wisdom on how to reply here?

@rrelyea rrelyea added Functionality:Push Resolution:Question This issues appears to be a question, not a product defect labels Sep 16, 2019
@rrelyea rrelyea changed the title Invalid or unrecognized response dotnet nuget push to GPR -- Invalid or unrecognized response Sep 16, 2019
@anangaur
Copy link
Member

/cc: @infin8x

Unfortunately, GPR does not work with API keys as we would have expected it to work. I have provided this feedback to GitHub.

You would need to use nuget sources add command to add GPR as a source with the creds (GITHUB.TOKEN). See an example here: https://github.com/anangaur/entropy-packages/blob/master/.github/workflows/workflow.yml

    steps:
    - uses: actions/checkout@v1
    - name: Setup Nuget.exe
      uses: warrenbuckley/Setup-Nuget@v1
    - name: Add GPR Source
      run: nuget sources add -name "GPR" -Source https://nuget.pkg.github.com/anangaur/index.json -Username anangaur -Password ${{ secrets.GITHUB_TOKEN }}
    - name: dotnet build
      run: dotnet build
    - name: nuget push
      run: nuget push my.sample.lib\**\*.nupkg -Source "GPR" -SkipDuplicate

Btw, there is a typo in your yaml file. Look for use of nupk instead of nupkg (missing 'g').

@jwillmer
Copy link
Author

jwillmer commented Sep 18, 2019

warrenbuckley/Setup-Nuget@v1 only installs nuget for Windows. Using your workaround on Linux via sudo apt install nuget does not work.
WARNING: No API Key was provided and no API Key could be found for 'https://nuget.pkg.github.com/NAME'. To save an API Key for a source use the 'setApiKey' command.

@anangaur
Copy link
Member

@jwillmer, you are right. We need to support dotnet sources command: #4126

@Talento90
Copy link

When I execute the following command: nuget push "ProjectFolder\nupkgs\MyPackage.1.0.0.nupkg" -Source "GitHub"

I get this error:
WARNING: No API Key was provided and no API Key could be found for 'https://nuget.pkg.github.com/Company'. To save an API Key for a source use the 'setApiKey' command.

Can anyone explain why? Since it's related with @jwillmer problem.

@jwillmer
Copy link
Author

Can anyone explain why? Since it's related with @jwillmer problem.

Please read the thread and you will find your answer.

@cilerler
Copy link

cilerler commented Oct 6, 2019

@rrelyea, It should work in non-windows builds. Would you please change this as a bug and not a question? Thanks in advance.

mhutch added a commit to mono/t4 that referenced this issue Oct 16, 2019
@mhutch
Copy link

mhutch commented Oct 16, 2019

I'm also seeing this using mono nuget.exe to publish to GPR on the Ubuntu image.

@anangaur
Copy link
Member

Did you check my comment above #8580 (comment)? Does it work?

@mavaa
Copy link

mavaa commented Oct 16, 2019

Managed to get this working for linux by creating a nuget.config "template" in my repo like this one: https://gist.github.com/marza91/06dd1a8af3abd85dd0c1972f22bbfc2d

I added this file (replace "ourcompany" with your user/org) to the base of the repo as ".nuget.config", and then simply did the following:

name: Build & Publish nuget package

on:
  push:
    branches: 
      - release

jobs:
  build:

    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v1
    - name: Setup .NET Core
      uses: actions/setup-dotnet@v1
      with:
        dotnet-version: 3.0.100
    - name: Build with dotnet
      run: dotnet build --configuration Release
    - name: Setup nuget config
      run: sed 's/GITHUB_TOKEN/${{ secrets.GITHUB_TOKEN }}/g' .nuget.config > nuget.config
    - name: Publish nuget
      run: dotnet nuget push src/bin/Release/*.nupkg -s "github"

The sed command simply copies the file to "nuget.config" and replaces "GITHUB_TOKEN" with the environment variable 🙂

@mhutch
Copy link

mhutch commented Oct 16, 2019

@anangaur I was doing pretty much the exact same thing but running nuget.exe on Mono, because the host is Ubuntu - mono/t4@863011b

@mikkeljohnsen
Copy link

When will this be fixed ?

@anangaur
Copy link
Member

@mikkeljohnsen What are you blocked on? Restoring packages or publishing packages?

Did you check the current workarounds? #8580 (comment)

@Konard
Copy link

Konard commented Oct 21, 2019

@marza91 you don't need to install .NET Core 3.0 when using ubuntu-latest in GitHub Actions, it is already there (the latest version, and also mono). So can safely remove this step:

    - name: Setup .NET Core
      uses: actions/setup-dotnet@v1
      with:
        dotnet-version: 3.0.100

Btw, I use windows as a workaround for now:
https://github.com/mono/t4/blob/573d5bb32be4b2b8ae13230cbc7eb56fcd9f9f99/.github/workflows/build.yml#L54-L58
https://github.com/linksplatform/Hardware.Cpu/blob/2e536836dd94dcfa8aa9840c99f50a9eb4a2c5a6/.github/workflows/main.yml#L42-L53

But it would be much better to have it working on linux too, I don`t want to use separate job for just this steps.

@mhutch
Copy link

mhutch commented Oct 21, 2019

@Konard TBH though I was annoyed by this initially, after I set up a matrix build I'm fine with having it in a later job, because that way the package only gets uploaded if all the matrix builds pass

@mikkeljohnsen
Copy link

mikkeljohnsen commented Oct 22, 2019

@anangaur I'm not familiar with that. But I assume it is something that is done on GitHub after you push your code to the branche "release".

I do not build my NuGet packages with dotnet/msbuild. I have +200 projects in my solution and using MSBuild is simple a pain, not to mention using NuGet for all +200 projects. It is simple to slow.

I use Makefiles (and mono "csc") to build my projects and also create NuGet packages with "nuget pack *.nuspec" and the "nuget push" to upload. But the "nuget push" is failing.

I'm on Linux (Fedora 30). Using Mono 6.0.

@mikkeljohnsen
Copy link

mikkeljohnsen commented Oct 22, 2019

So now "dotnet nuget push *.pkpkg -s GitHub", works sometimes. I have uploaded 2 packages out of 20. So just have to run the command a 100 times, then maybe all packages will be successfully uploaded :)

Must be something wrong with the GitHub server, since it works sometimes.

@anangaur
Copy link
Member

@mikkeljohnsen intermittent failures are hard to fix. Can you paste the error messages you have been getting?

@jwillmer
Copy link
Author

I tried @marza91 script but I get

warn : No API Key was provided and no API Key could be found for 'https://nuget.pkg.github.com/COMPANY'. To save an API Key for a source use the 'setApiKey' command.
info: Pushing ...
error: An error occurred while sending the request.
error: The response ended prematurely.

I think the warning can be ignored since we provide user/pw in the NuGet file.
But I don't know if this error is because I already have the current version of the NuGet package deployed or if it is something else. In my version is used -SkipDuplicate to ignore published duplicates but this is not possible with dotnet nuget

@mikkeljohnsen
Copy link

mikkeljohnsen commented Oct 23, 2019

@anangaur

As you can see the first package is already uploaded and it reports correctly that there is a conflict.

warn : No API Key was provided and no API Key could be found for 'https://nuget.pkg.github.com/openmedicus'. To save an API Key for a source use the 'setApiKey' command.
info : Pushing OpenMedicus.WebService.Master.2.6.105.nupkg to 'https://nuget.pkg.github.com/openmedicus'...
info :   PUT https://nuget.pkg.github.com/openmedicus/
warn : Error: Version OpenMedicus.WebService.Master of "2.6.105" has already been pushed.
info :   Conflict https://nuget.pkg.github.com/openmedicus/ 445ms
error: Response status code does not indicate success: 409 (Conflict).

But pushing new packages almost always fails.

warn : No API Key was provided and no API Key could be found for 'https://nuget.pkg.github.com/openmedicus'. To save an API Key for a source use the 'setApiKey' command.
info : Pushing OpenMedicus.RosterHelper.2.6.105.nupkg to 'https://nuget.pkg.github.com/openmedicus'...
info :   PUT https://nuget.pkg.github.com/openmedicus/
info : An error was encountered when fetching 'PUT https://nuget.pkg.github.com/openmedicus/'. The request will now be retried.
info : An error occurred while sending the request.
info :   The response ended prematurely.
info :   PUT https://nuget.pkg.github.com/openmedicus/
info : An error was encountered when fetching 'PUT https://nuget.pkg.github.com/openmedicus/'. The request will now be retried.
info : An error occurred while sending the request.
info :   The response ended prematurely.
info :   PUT https://nuget.pkg.github.com/openmedicus/
error: An error occurred while sending the request.
error:   The response ended prematurely.

Somtimes I also get (this is using "nuget push" and not "dotnet nuget push" as above):

Pushing OpenMedicus.Data.2.6.105.nupkg to 'https://nuget.pkg.github.com/openmedicus'...
  PUT https://nuget.pkg.github.com/openmedicus/
An error was encountered when fetching 'PUT https://nuget.pkg.github.com/openmedicus/'. The request will now be retried.
Error while copying content to a stream.
  Unable to write data to the transport connection: The socket has been shut down.
  The socket has been shut down
  PUT https://nuget.pkg.github.com/openmedicus/
An error was encountered when fetching 'PUT https://nuget.pkg.github.com/openmedicus/'. The request will now be retried.
Error while copying content to a stream.
  Unable to write data to the transport connection: The socket has been shut down.
  The socket has been shut down
  PUT https://nuget.pkg.github.com/openmedicus/
Error while copying content to a stream.
  Unable to write data to the transport connection: The socket has been shut down.
  The socket has been shut down

@anangaur
Copy link
Member

anangaur commented Oct 23, 2019

@mikkeljohnsen Are you using the right PAT while adding the GPR source? With nuget.exe you can run:

nuget sources add -name "GPR" -Source https://nuget.pkg.github.com/<account>/index.json -Username <user> -Password <PAT>

And for dotnet, see #8580 (comment)

@mikkeljohnsen
Copy link

@anangaur Yes I do. I have managed to upload 2 packages.

It is a TOKEN you have to use, and it has all the possible security rights set.

@Dids
Copy link

Dids commented Oct 29, 2019

So does this only work reliably on Windows, while macOS and Linux only work intermittently?

I've yet to see pushing work at all on macOS. Not locally and not on a CI/GitHub Actions.

It almost sounds like the NuGet specific endpoint/service is stuck in an exception loop:

Pushing <PKG>.<VER>.nupkg to 'https://nuget.pkg.github.com/<ORG>'...
  PUT https://nuget.pkg.github.com/<ORG>/
An error was encountered when fetching 'PUT https://nuget.pkg.github.com/<ORG>/'. The request will now be retried.
An error occurred while sending the request.
  Unable to write data to the transport connection: The socket has been shut down.
  The socket has been shut down
  PUT https://nuget.pkg.github.com/<ORG>/
An error was encountered when fetching 'PUT https://nuget.pkg.github.com/<ORG>/'. The request will now be retried.
An error occurred while sending the request.
  Unable to write data to the transport connection: The socket has been shut down.
  The socket has been shut down
  PUT https://nuget.pkg.github.com/<ORG>/
An error occurred while sending the request.
  The server returned an invalid or unrecognized response.

@daltskin
Copy link

Also been through a few iterations and approaches to this. Sometimes the following works, other times I get errors:

    - name: Publish to github
      run: dotnet nuget push **/*.nupkg -s https://nuget.pkg.github.com/[USERNAME]/index.json -k ${{ secrets.GITHUB_TOKEN }} --skip-duplicate --no-symbols true
      working-directory: src

[intermittent] errors with: An error was encountered when fetching 'PUT https://nuget.pkg.github.com/daltskin/'. The request will now be retried. An error occurred while sending the request.

Now, I'm just using curl to push the package and it seems more reliable :)

Replace [PACKAGE] with your package name
Replace [USERNAME] with your username

Github workflow extract:

    - name: Package
      run: dotnet pack --configuration Release --no-build -p:PackageVersion=${{ env.GitVersion_SemVer}}
    
    - name: Publish to github (using curl)
      run: curl -vX PUT -u "[USERNAME]:${{ secrets.GITHUB_TOKEN }}" -F package=@[PACKAGE].${{ env.GitVersion_SemVer}}.nupkg https://nuget.pkg.github.com/[USERNAME]/
      working-directory: src/bin/Release

@RehanSaeed
Copy link

RehanSaeed commented Jul 10, 2020

I have two repos where I'm using the exact same build.yml file and one fails while the other does not. The only difference is that one project has a . in the name (Schema.NET) while the other (FastestNuGet) does not. There doesn't seem to be any issues tracking this.

Run dotnet nuget push .\windows-latest\*.nupkg --source GitHub --skip-duplicate
warn : No API Key was provided and no API Key could be found for 'https://nuget.pkg.github.com/RehanSaeed'. To save an API Key for a source use the 'setApiKey' command.
Pushing Schema.NET.7.1.1-preview.0.33.nupkg to 'https://nuget.pkg.github.com/RehanSaeed'...
  PUT https://nuget.pkg.github.com/RehanSaeed/
An error was encountered when fetching 'PUT https://nuget.pkg.github.com/RehanSaeed/'. The request will now be retried.
Error while copying content to a stream.
  Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
  An existing connection was forcibly closed by the remote host.
  PUT https://nuget.pkg.github.com/RehanSaeed/
An error was encountered when fetching 'PUT https://nuget.pkg.github.com/RehanSaeed/'. The request will now be retried.
Error while copying content to a stream.
  Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
  An existing connection was forcibly closed by the remote host.
  PUT https://nuget.pkg.github.com/RehanSaeed/
error: Error while copying content to a stream.
error:   Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
error:   An existing connection was forcibly closed by the remote host.
name: Build

on:
  push:
  pull_request:
  release:
    types:
      - published

env:
  # Set the DOTNET_SKIP_FIRST_TIME_EXPERIENCE environment variable to stop wasting time caching packages
  DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
  # Disable sending usage data to Microsoft
  DOTNET_CLI_TELEMETRY_OPTOUT: true
  # Set the build number in MinVer
  MINVERBUILDMETADATA: build.${{github.run_number}}

jobs:
  build:
    name: Build-${{matrix.os}}
    runs-on: ${{matrix.os}}
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macOS-latest]
    steps:
    - name: 'Checkout'
      uses: actions/checkout@v2
      with:
        lfs: true
        fetch-depth: 0
    - name: 'Git Fetch Tags'
      run: git fetch --tags
      shell: pwsh
    - name: 'Install .NET Core SDK'
      uses: actions/setup-dotnet@v1
      with:
        dotnet-version: 3.1.301
    - name: 'Dotnet Tool Restore'
      run: dotnet tool restore
      shell: pwsh
    - name: 'Dotnet Cake Build'
      run: dotnet cake --target=Build
      shell: pwsh
    - name: 'Dotnet Cake Test'
      run: dotnet cake --target=Test
      shell: pwsh
    - name: 'Dotnet Cake Pack'
      run: dotnet cake --target=Pack
      shell: pwsh
    - name: 'Publish Artefacts'
      uses: actions/[email protected]
      with:
        name: ${{matrix.os}}
        path: './Artefacts'

  push-github-packages:
    name: 'Push GitHub Packages'
    needs: build
    if: github.ref == 'refs/heads/master' || github.event_name == 'release'
    runs-on: windows-latest
    steps:
      - name: 'Download Artefact'
        uses: actions/download-artifact@v1
        with:
          name: 'windows-latest'
      - name: 'Dotnet NuGet Add Source'
        run: dotnet nuget add source https://nuget.pkg.github.com/RehanSaeed/index.json --name GitHub --username RehanSaeed --password ${{secrets.GITHUB_TOKEN}}
        shell: pwsh
      - name: 'Dotnet NuGet Push'
        run: dotnet nuget push .\windows-latest\*.nupkg --source GitHub --skip-duplicate
        shell: pwsh

@rido-min
Copy link

I got it working with dotnet nuget push here
.. but didnt work when using a repo under a GitHub organization, so I switched to curl

@Fronix
Copy link

Fronix commented Sep 15, 2020

I'm using my nuget action under an organization and this is what's been working for us after many trial and errors.

      - name: Publish backend nuget
        run: curl -vX PUT -u "user:${{ secrets.package_secret }}" -F package=@Publish/backend.${{env.VERSION}}.nupkg https://nuget.pkg.github.com/myorg/
        shell: bash
        working-directory: ${{env.backend-directory}}
      - name: Publish frontend nuget
        run: curl -vX PUT -u "user:${{ secrets.package_secret }}" -F package=@Publish/backend.${{env.VERSION}}.nupkg https://nuget.pkg.github.com/myorg/
        shell: bash
        working-directory: ${{env.frontend-directory}}

@Airn5475
Copy link

I know this issue is closed, but I continue to see issues with the methods mentioned above. One time it works and then another time it doesn't. I am also working under and organization. This is SO Frustrating!

@anangaur
Copy link
Member

anangaur commented Sep 17, 2020

Hey All, I can understand this can be frustrating. For the team to have visibility and help here, I have created a new issue:
Reliability issues while publishing packages to GPR, using GitHub Actions) #10045

Please provide your experience/issues and upvotes on this new issue. Hope this helps.

@Airn5475
Copy link

I reached out to GitHub Enterprise Support and here's what they shared with me:

Sorry for the trouble here -- we're aware of an issue that seems to affect some .nupkg files, but not others and our engineering team is working to isolate the issue causing this behaviour when pushing nuget packages to the GitHub Package Registry.

Please try the following alternative methods to push your package and let us know if that works for you:

curl -vX PUT -u "<username>:<TOKEN>" -F [email protected] https://nuget.pkg.github.com/<OWNER>/

Another alternative method is to push using the gpr tool:

dotnet tool install gpr -g
gpr push PATH-TO-PKG-FILE.nupkg -k <TOKEN>

Here is how I used the GPR Tool in my GitHub Action and it worked the first time!

$file = Get-ChildItem -Path <where I output my nupkg file to> -Recurse -Filter *.nupkg | Select -First 1
gpr push $file.FullName -k ${{secrets.GITHUB_TOKEN}}

https://stackoverflow.com/a/63943965/229897

@vpenades
Copy link

@Airn5475 gpr might not be an option for some users like me.

Something not everybody knows is that nuget.config files are evaluated in cascade from the root directory to the current directory. So nuget.config files in between the root and the current directory can add, remove or override existing properties. I use this particular behaviour to split the login keys and the actual nuget server in two separated nuget.config files, so I can add the nuget.config with the servers to the repository, and leave the nuget.config with the login keys out of it.

nuget cli app and visual studio handles this feature perfectly, whereas gpr only reads the properties of the first nuget.config it finds.

In fact, I suspect this way of handling nuget.configs is one of the reasons because it works for some users, and not for others.

@Airn5475
Copy link

@vpenades I hear you, this isn't for everyone, but I saw others in the comments above having trouble with dotnet push and so I thought it best to share my solution. Better to perhaps help some then for sure help none, right?

I am aware of the nuget.config cascade and have wrestled with it a couple times. That was not my issue this time since my files were all in order and a repo that HAD been publishing nuget packages fine, stopped working.

I can't speak to others, but gpr fixed my issue today!

@jamesbayley
Copy link

jamesbayley commented Sep 21, 2020

More recently I've noticed a general improvement in the frequency of success messages vs. failure messages. I've also found that in the few instances that it doesn't work, going away for a coffee and coming back 10 minutes later to retry is usually sufficient to achieve a successful push. Not an ideal solution, but at least you get a coffee out of it!

Anyway, I've included both my NuGet.config file and a deploy-package.ps1 script that I've written to ease this process. Just to note that the deploy-package script was primarily written for .NET Core/.NET Standard 2.1 (but seems to work fine with .NET Framework scripts too). The deploy-package and NuGet.config files must reside in your root folder (at same level as .sln file) and make an implicit assumption that the .csproj file is in a subdirectory (i.e. src folder etc.), so your project structure should look as follows:

  • {solutionName}.sln
  • NuGet.config
  • deploy-package.ps1
  • src
    • {projectName}.csproj

You could revamp the deploy-package script for other folder arrangements, but this was ideal for my team's workflow.

Anyway, here are the files (replace repo name as required):

  1. NuGet.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <packageSources>
        <clear />
        <add key="nuget" value="https://api.nuget.org/v3/index.json" />
        <add key="github" value="https://nuget.pkg.github.com/**REPOSITORY-NAME**/index.json" />        
    </packageSources>
    <packageSourceCredentials>
        <github>
            <add key="Username" value="%GITHUB_USERNAME%" />
            <add key="ClearTextPassword" value="%GITHUB_TOKEN%" />
        </github>
    </packageSourceCredentials>
</configuration>
  1. deploy-package.ps1
# Powershell Script identifies the latest built NuGet Package and uploads to GitHub Packages.

# Functions to define coloured messages for SUCCESS and ERROR statements.
function Write-Success{Write-Host "SUCCESS:" -ForegroundColor Green -NoNewLine}
function Write-Error{Write-Host "ERROR:" -ForegroundColor Red -NoNewLine}

# Store the initial working directory to return the user back to this folder during clean-up.
$startingDir = Get-Location

# Gets the location of the calling script.
# This file should be inside the top level of the respective dotnet project in the same level as the .sln file.
$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path

# Sets the working directory to the location of the project to build.
Set-Location "$ScriptDir/src"

# Builds Project to ensure .nupkg file is present.
# Note: this assumes <generatePackageOnBuild> tag in .csproj file is set to true.
Write-Host "Building Project to Generate .nupkg File..."
dotnet build --configuration Release
Write-Host "$(Write-Success) Build Complete."
Write-Host ""

# Identifying the most recent .nupkg file.
# Finds all children in bin/Release/netstandard2.1, which contains .nupkg files.
Write-Host "Finding Most Recent .nupkg File..."
$latestPackage = Get-ChildItem -path "./bin/Release/netstandard2.1" | 
                 Sort-Object -Property LastWriteTime |
                 Select-Object -last 1 
Write-Host "$(Write-Success) Most Recent Package Found."
Write-Host ""

# Extracting baseName from file.
$latestPackageBaseName = $latestPackage.baseName
Write-Host "$(Write-Success) baseName Retrieved: $latestPackageBaseName"
Write-Host ""

# Publishing Package to GitHub (assuming Token Configuration already complete).
Write-Host "Attempting to Deploy to GitHub..."
try {
    dotnet nuget push "./bin/Release/netstandard2.1/$latestPackageBaseName.nupkg" --skip-duplicate -s "github" -k $env:NUGET_KEY
    Write-Host ""
}
# Regardless of success of package push, 
# reset variables and working directory location.
finally {
    # Clean Up.
    Write-Host "Cleaning up variables..."
    Set-Location $startingDir
    $latestPackage = ""
    $latestPackageBaseName = ""
    Write-Host "Powershell Script clean up complete."
}

Just a note for those who've never had to set environment variables, it's very straightforward. Simply follow the steps below:

  1. Open either Windows PowerShell or PowerShell Core.
  2. Assuming VSCode, type code $profile.CurrentUserAllHosts
  3. Add the following environment variables within the code editor:
    $Env:NUGET_KEY="...",
    $Env:GITHUB_USERNAME="...",
    $Env:GITHUB_TOKEN="..."
  4. You get your NUGET_KEY from the NuGet website.
  5. You get your GITHUB_USERNAME and GITHUB_TOKEN from GitHub - make sure you set correct privileges.
  6. Save editor, and reopen a fresh terminal (otherwise new variables are inaccessible).
  7. Then you can run the ./deploy-package.ps1 script provided above.

Just a final comment that Visual Studio can interfere with NuGet.config file! If working in Visual Studio, you can avoid needing the NuGet.config file altogether by running the following command in PowerShell (just a one-time thing!) and you set a system-wide source setting that will work across VS, PowerShell Core, Windows PowerShell etc:

dotnet nuget add source "https://nuget.pkg.github.com/**REPOSITORY-NAME**/index.json" --name "github" --username $Env:GITHUB_USERNAME --password $Env:GITHUB_TOKEN --store-password-in-clear-text

The deploy-package script will still work as expected.

This source setting is saved here on Windows: {Home}\{user}\AppData\Roaming\NuGet

This issue is intermittent, but the info above should increase your odds of success until it's fixed! If at first you don't succeed, get a coffee and try later ;)

Cheers.

@fskuteken
Copy link

I was able to make it work using the following command:

nuget push ProjectName/bin/Release/ProjectName.x.y.z.nupkg -source "github"

Previously, using dotnet nuget push ProjectName/bin/Release/ProjectName.x.y.z.nupkg --source "github" was leading to warn : No API Key was provided and no API Key could be found for 'https://nuget.pkg.github.com/ORGANIZATION_NAME'. To save an API Key for a source use the 'setApiKey' command. for me.

My nuget.config file is the following:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <clear />
    <add key="nuget" value="https://api.nuget.org/v3/index.json" />
    <add key="github" value="https://nuget.pkg.github.com/ORGANIZATION_NAME/index.json" />
  </packageSources>
  <packageSourceCredentials>
    <github>
      <add key="Username" value="%GITHUB_USERNAME%" />
      <add key="ClearTextPassword" value="%GITHUB_TOKEN%" />
    </github>
  </packageSourceCredentials>
</configuration>

@jcansdale
Copy link

jcansdale commented Oct 22, 2020

Hi @jwillmer,

You should find the following works fine now:

      - name: Publish Nuget to GitHub registry
        run: dotnet nuget push ./MyNugetPackage.3.4.24.nupk -k ${GITHUB_TOKEN} -s https://nuget.pkg.github.com/USERNAME/index.json  
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Support for the dotnet nuget push --api-key option has now been added to GitHub Packages. For some reason this works consistently, but using basic auth (password in nuget.config file) fails randomly!

@jwillmer
Copy link
Author

@jcansdale I referenced your solution on stackoverflow: How to push nuget package in GitHub actions

@jcansdale
Copy link

@jwillmer,

Thanks for the heads up!

BTW, your example workflow can now look like this (no need for source-url in setup-dotnet):

      - name: Setup .NET Core @ Latest
        uses: actions/setup-dotnet@v1
        with:
          dotnet-version: '3.1.x'
          
      - name: Build solution and generate NuGet package
        run: |  
          cd <project>
          dotnet pack -c Release -o out  

      - name: Push generated package to GitHub registry
        run: dotnet nuget push ./<project>/out/*.nupkg --source https://nuget.pkg.github.com/<owner> --api-key ${{github.token}} --skip-duplicate --no-symbols true

JBildstein added a commit to JBildstein/SpiderEye that referenced this issue Nov 28, 2020
using the API key should be supported now, see NuGet/Home#8580
@lettucemode
Copy link

lettucemode commented Feb 12, 2021

Just leaving my solution here since I stumbled across this while googling for solutions. I am not using a nuget.config and I am using the standard dotnet pack and dotnet push commands.

When I was getting the api-key error (as others have described above), there was a second error message after it related to RepositoryUrl not being set. This is a setting in the .csproj file. The official documentation on this point is a little misleading because it only mentions adding this setting in the section about using a nuget.config, but I ended up needing it for my case too.

<PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <RepositoryUrl>https://github.com/GITHUB_REPOSITORY</RepositoryUrl>
</PropertyGroup>

Apparently this needs to be the URL to the repo this action is running for. I set my value as above and then used a small sed command to replace that value during a run (thanks to the person above who did something similar):

sed -i s#GITHUB_REPOSITORY#${{ github.repository }}#g Project.csproj

After doing these steps the publish was successful, but I was still getting a warning because of the missing api key. I added this to the nuget push line as suggested in the post before this one, and now everything is working with no error or warnings, and no need for any extra repository secrets or nuget-related files.

Here's my final (anonymized) workflow:

name: Publish Package

on:
  push:
    branches:
      - main
      - 'releases/**'
    paths:
      - 'src/Project/**'

env:
  DOTNET_VERSION: '3.1.x'
  PACKAGE_MAJOR_VERSION: 0
  PACKAGE_MINOR_VERSION: 0
  REPOSITORY_URL: https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json

jobs:
  build:
    runs-on: ubuntu-latest
    name: Update NuGet Package
    steps:
      - name: Checkout repository
        uses: actions/checkout@v2
        with:
          submodules: recursive

      - name: Install dotnet SDK ${{ env.DOTNET_VERSION }}
        uses: actions/setup-dotnet@v1
        with:
          dotnet-version: ${{ env.DOTNET_VERSION }}

      - name: Build & package project
        run: |
          PACKAGE_VERSION=$PACKAGE_MAJOR_VERSION.$PACKAGE_MINOR_VERSION.$GITHUB_RUN_NUMBER
          cd src/Project
          sed -i s#GITHUB_REPOSITORY#${{ github.repository }}#g Project.csproj
          dotnet pack -c Release -o out -p:PackageVersion=$PACKAGE_VERSION

      - name: Push to GitHub package registry
        run: dotnet nuget push ./src/Project/out/*.nupkg --source ${{ env.REPOSITORY_URL }} --api-key ${{ secrets.GITHUB_TOKEN }} --skip-duplicate --no-symbols true

Hope this helps someone out there.

365Erez added a commit to ErezG/POC_demo_package that referenced this issue Mar 25, 2021
365Erez added a commit to ErezG/POC_demo_package that referenced this issue Mar 25, 2021
365Erez added a commit to ErezG/POC_demo_package that referenced this issue Mar 25, 2021
365Erez added a commit to ErezG/POC_demo_package that referenced this issue Mar 25, 2021
hf-aschloegl added a commit to Hochfrequenz/BO4E-dotnet that referenced this issue Sep 15, 2021
hf-aschloegl added a commit to Hochfrequenz/BO4E-dotnet that referenced this issue Sep 15, 2021
Error: UserName: Password:   Unauthorized https://nuget.pkg.github.com/hochfrequenz/ 564ms
Response status code does not indicate success: 401 (Unauthorized).

Try to keep as close as possible to NuGet/Home#8580
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Functionality:Push Resolution:Question This issues appears to be a question, not a product defect
Projects
None yet
Development

No branches or pull requests