GitHub Actions for .NET: Complete CI/CD Guide

GitHub Actions has rapidly matured since its 2019 launch. For .NET developers, it offers a distinct advantage over Azure DevOps: the workflow lives right next to the code, and the marketplace for actions is exploding. This guide shows how to build a robust CI/CD pipeline for a .NET Core 3.1 Web API, including unit testing, Nuget caching, and Azure deployment.

The Workflow Structure

graph LR
    Push[git push] --> JobBuild[Job: Build]
    JobBuild --> Restore[dotnet restore]
    Restore --> Build[dotnet build]
    Build --> Test[dotnet test]
    Test --> Pack[dotnet publish]
    Pack --> Artifact[Upload Artifact]
    
    Artifact --> JobDeploy[Job: Deploy]
    JobDeploy --> Login[Azure Login]
    Login --> WebApp[Deploy to WebApp]
    
    style JobBuild fill:#E1F5FE
    style JobDeploy fill:#FFF3E0

Caching NuGet Packages

Speed up builds by caching `~/.nuget/packages`. This is one of the most effective optimizations for .NET builds.

steps:
- uses: actions/checkout@v2

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

- name: Cache NuGet packages
  uses: actions/cache@v2
  with:
    path: ~/.nuget/packages
    key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj') }}
    restore-keys: |
      ${{ runner.os }}-nuget-

- name: Install dependencies
  run: dotnet restore

Running Tests with Coverage

We use `coverlet.collector` to generate coverage reports and upload them to Codecov or minimal pipeline artifacts.

- name: Test with Coverage
  run: dotnet test --no-restore --collect:"XPlat Code Coverage"

- name: Upload coverage to Codecov
  uses: codecov/codecov-action@v1
  with:
    token: ${{ secrets.CODECOV_TOKEN }}

Deploying to Azure App Service

We recommend using the Publish Profile method for simplicity, or Service Principal for RBAC control.

- name: Azure WebApp
  uses: azure/webapps-deploy@v2
  with:
    app-name: 'my-api-prod'
    publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }} 
    package: ./publish

Key Takeaways

  • GitHub Actions implementation is YAML-based, similar to Azure Pipelines but more integrated with events.
  • Caching NuGet reduces build times by 50%+.
  • Secrets management is repository-scoped; use Environment Secrets for production gates.

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.