CI/CD for .NET Projects: GitHub Actions and Azure Pipelines

Build CI/CD for .NET projects: restore, build, test, publish, NuGet caching, matrix builds, coverage, artifacts, and versioning in equivalent YAML.

Executive Summary: CI/CD for .NET projects is a short sequence done well: restore, build, test, publish, artifact, deploy, with NuGet caching so the first two are fast, a pinned SDK so the build is reproducible, and artifacts so deploy jobs move files rather than rebuild them. GitHub Actions and Azure Pipelines express the same pipeline in different YAML, and this page shows both, side by side.

The scene this page exists to prevent: a deployment performed from a developer’s laptop with a version of the code that is not on main, built in Debug because the flag was forgotten, and shipped with the wrong connection string because appsettings had it. Everything wrong there is fixed by one artifact, a pipeline, that does the same steps the same way every time and refuses to deploy what it did not build.

CI/CD for .NET projects means the dotnet commands wrapped in pipeline YAML. Restore and build to compile, test to gate, publish and artifacts to package, deploy to ship. The GitHub Actions documentation and the Azure Pipelines documentation are the platform references; the NuGet restore behavior is what the caching stages wrap.

The examples build the TaskApi on .NET SDK 10.0 and run the xUnit and WebApplicationFactory test suites from the testing guides. Deploy through the pattern in the App Service guide.

Maintaining pipelines that teams trusted, and ones they routed around, taught me this: the pipeline is a team member that reviews every commit. As a result, it deserves review-quality YAML, pinned versions, and a fast response time, or it becomes the member whose findings get dismissed.

The .NET pipeline stages

Every .NET CI/CD pipeline, on either platform, is the same six steps in the same order:

Stage Command or step What it protects
Restore dotnet restore (often implicit in build) Dependency resolution, cached for speed
Build dotnet build --configuration Release Compiles what the tests will run against
Test dotnet test The gate: unit and integration suites must pass
Publish dotnet publish -c Release The deployable output, built once
Artifact Upload/publish the publish folder Deploy jobs move the exact tested bytes
Deploy Platform’s deploy step Same artifact to staging, then production

The invariant inside the table is the one that matters: the artifact that is deployed is the artifact that was tested. Pipelines that rebuild in the deploy job have tested one binary and shipped another, which is the laptop-deploy failure mode wearing a pipeline costume.

GitHub Actions: the full workflow

name: build-and-test
on:
  pull_request:
  push:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@<full-commit-sha>  # v5 (resolve the current SHA)

      - uses: actions/setup-dotnet@<full-commit-sha>  # v5 (resolve the current SHA)
        with:
          dotnet-version: '10.0.x'
          cache: true
          cache-dependency-path: '**/packages.lock.json'

      - run: dotnet restore TaskApi.sln

      - run: dotnet build TaskApi.sln --configuration Release --no-restore

      - run: dotnet test TaskApi.sln --configuration Release --no-build
             --logger trx --collect:"XPlat Code Coverage"

      - run: dotnet publish TaskApi/TaskApi.csproj -c Release -o ./publish

      - uses: actions/upload-artifact@<full-commit-sha>  # v5 (resolve the current SHA)
        with:
          name: taskapi
          path: ./publish

Reading the parts that earn their lines: the SDK action pins a 10.0.x version band so the pipeline never builds with a different compiler than your global.json expects. cache: true with a lockfile path makes restore a few seconds instead of a few minutes. --no-restore and --no-build stop the test step from silently recompiling everything. Every third-party action is pinned to a full commit SHA with the version in a comment. This is because a mutable tag in a pipeline is a supply-chain hole. The trx logger and coverage collector make results visible in the Actions summary at orientation level.

Azure Pipelines: the same build

trigger:
  branches: { include: [ main ] }
pr: [ main ]

pool: { vmImage: ubuntu-latest }

variables:
  buildConfiguration: Release

steps:
  - task: DotNetCoreCLI@2
    displayName: restore
    inputs:
      command: restore
      projects: TaskApi.sln

  - task: DotNetCoreCLI@2
    displayName: build
    inputs:
      command: build
      projects: TaskApi.sln
      arguments: --configuration $(buildConfiguration) --no-restore

  - task: DotNetCoreCLI@2
    displayName: test
    inputs:
      command: test
      projects: TaskApi.sln
      arguments: --configuration $(buildConfiguration) --no-build
      publishTestResults: true

  - task: DotNetCoreCLI@2
    displayName: publish
    inputs:
      command: publish
      projects: TaskApi/TaskApi.csproj
      arguments: --configuration $(buildConfiguration) -o $(Build.ArtifactStagingDirectory)/publish

  - task: PublishBuildArtifacts@1
    inputs:
      pathToPublish: $(Build.ArtifactStagingDirectory)/publish
      artifactName: taskapi

The mapping is one to one: DotNetCoreCLI@2 tasks replace raw run: steps, the artifact staging directory replaces the upload-artifact action. Test results publish into the pipeline UI automatically. Teams already using Azure DevOps for repos and boards typically keep the pipeline there. Teams on GitHub get the same behavior with fewer concepts to translate.

NuGet caching: the minutes you get back first

Restore is usually the slowest CI step before caching, because a clean runner downloads every package every run. The fix has two parts: lockfiles, so the cache key changes only when dependencies change, and the cache itself.

  • GitHub Actions: actions/setup-dotnet with cache: true and cache-dependency-path pointing at the lockfiles (enable lockfiles with RestorePackagesWithLockFile in the csproj).
  • Azure Pipelines: the Cache@2 task keyed on the lockfile hash, caching the global packages folder (~/.nuget/packages).

Measure before and after with the pipeline’s own timing report. The restore step should drop from minutes to seconds. Every later stage inherits the saved time across hundreds of runs.

Matrix builds: one workflow, many targets

When a project must hold on several targets (a library supporting multiple .NET versions and operating systems), a matrix expands one job into a grid:

strategy:
  matrix:
    os: [ ubuntu-latest, windows-latest ]
    tfm: [ net8.0, net10.0 ]
  fail-fast: false

Use matrices for libraries and genuinely cross-platform code. A single-target web API on one Linux runner needs none of this. A matrix that exists to look thorough is four times the pipeline minutes for one time the information.

Test reports and coverage, at orientation level

Both platforms render test results without extra tooling: the trx logger in the Actions example and publishTestResults in the Pipelines example put pass and fail counts, timings, and failure details in the UI where every reviewer sees them. Coverage collection is one flag (--collect:"XPlat Code Coverage"), producing the coverage file the pipelines can attach. At orientation level, the advice is: turn both on, let the report exist, and do not gate on a coverage percentage. Dashboards and quality gates are tooling decisions beyond this page, and a percentage target without review of the covered logic is a number, not a guarantee.

Artifacts and versioning: what deploy actually receives

Between build and deploy sits the artifact, the tested bytes the deploy job downloads and ships. Versioning it so a deployment maps to a commit is the practice that makes “which build is on staging?” a query rather than a question:

  • Version sources: the csproj’s version prefix for the release, plus the pipeline run number as the build suffix (for example 1.2.0-ci.{runNumber} for CI builds), or a git tag when the release is cut from a tag.
  • Artifact naming: the run number in the artifact name, so five runs in a day are five distinguishable artifacts.
  • Deploy jobs download, never rebuild: the deploy stage fetches the artifact and uses the deploy step from the App Service guide, running migrations first when the release includes them, per the migrations guide.

When the artifact is a container image rather than a publish folder, the build-and-push stage is a different pipeline shape: that belongs to the Docker guide’s image build and push guide, and the manifest side of the cluster continues in its GitOps guide.

How real systems do this

  • Pull requests build and test. Main builds, tests, and deploys. The PR pipeline is the fast gate (restore cache, build, tests), and only main gets a deploy job, so no one deploys from an unmerged branch.
  • Secrets live in the pipeline’s secret stores. GitHub encrypted secrets and Azure DevOps variable groups, referenced as ${{ secrets.NAME }} and $(NAME). A value in YAML is a value in the repository, and the pipeline YAML is in the repository.
  • Pipeline speed is watched like app performance. Teams see run duration as a number with a trend. When it creeps past the attention span, caching and job splitting get the same scrutiny as a slow endpoint.

A situation I watched unfold is the red-main spiral: a flaky integration test failed on main, the deploy was overridden with a “ignore failing tests” flag just this once, the flag stayed, and within a month the team’s reflex to a red pipeline was a manual rerun. The actual flaky test got fixed in an afternoon once someone owned it. The harder work was restoring the reflex, which meant making the pipeline green and fast enough that red meant something again. The takeaway: the pipeline’s authority is a shared habit, and every override spends some of it.

Decision framework: shaping your pipeline

  1. Where does your code live? GitHub: Actions. Azure DevOps: Pipelines. The YAML differs; the stages do not, and the choice follows the platform your team already uses for code review.
  2. Is the suite slow enough to split? A full run past about ten minutes earns separated unit and integration jobs. As a result, unit failures surface in the first minute. Under that, one job is simpler.
  3. What should the cache key be? Lockfile hash (best), else the sum of all csproj files. The point is that dependency changes rebuild the cache and code changes do not.
  4. Does anything build more than once? No. Restore and build happen in the build job, tests reuse the build, the deploy job downloads the artifact. Rebuilding anywhere is the bug.
  5. What runs on pull requests? The same build and test stages as main, minus deploy. A PR that cannot pass the gate cannot merge.

When NOT to add pipeline machinery

  • Do not build container images in an app pipeline by reflex. Publish-folder artifacts cover zip and slot deployments. Image builds are a distinct pipeline with registry concerns, covered in the Docker guide’s build-and-push guide.
  • Do not deploy from pull request branches. PR pipelines verify; main deploys; anything else ships unreviewed code.
  • Do not chase a coverage gate before you read the reports. Coverage collection on, reports visible, no percentage target: the number does not say which lines matter.

Common mistakes

  • Mutable action and task references. Third-party actions pinned by tag can change under you. The full commit SHA with a version comment is the reviewable form.
  • No caching. Every run pays full restore cost, pipelines get slow, and slow pipelines get skipped; two lines of configuration remove the tax.
  • Secrets in YAML. The workflow file is code in the repository; secrets belong in encrypted stores and secret variables.
  • Deploy jobs that rebuild. Rebuilding in deploy breaks the tested-equals-shipped invariant; download the artifact.
  • Deploying before migrations. A release with schema changes applies them as a pipeline step before new instances start, or the deploy ships code against yesterday’s database.
  • Tolerating a red main branch. Every override and ignored failure teaches the team that the pipeline is optional. Flaky tests get fixed, because authority is easier kept than rebuilt.

The pipeline principles are not specific to .NET. See CI/CD for backend engineers for strategy, and setting up a CI/CD pipeline in AWS for another cloud.

Key takeaways

  • The .NET pipeline is six stages: restore, build, test, publish, artifact, deploy, and the deployable artifact is exactly the tested one.
  • GitHub Actions and Azure Pipelines express the same stages; setup-dotnet with caching versus DotNetCoreCLI tasks is translation, not redesign.
  • NuGet caching keyed on lockfiles takes restore from minutes to seconds; matrix builds serve multi-target libraries, not single-target APIs.
  • Test results and coverage attach to the run with one logger or flag each; read the reports before considering gates.
  • Version artifacts with the csproj version plus the run number or git tag, so any deployment maps back to a commit.
  • Pin third-party actions to full SHAs, keep secrets in the pipeline stores, run migrations before instances start, and never let main stay red.

FAQ

Should I use GitHub Actions or Azure Pipelines for .NET?

Follow where your code and reviews live: GitHub repositories pair naturally with Actions, and Azure DevOps repositories with Pipelines. Both run the same dotnet commands with caching, test reporting, artifacts, and deploy steps. The YAML syntax differs, but the pipeline stages are identical, so the choice is organizational, not technical.

How do I cache NuGet packages in CI?

In GitHub Actions, use actions/setup-dotnet with cache: true and cache-dependency-path pointing at your lockfiles. In Azure Pipelines, use the Cache@2 task keyed on the lockfile hash, caching the global packages folder. Either way, enable package lockfiles in your projects so the cache key changes only when dependencies change.

How do I run .NET tests in a pipeline?

dotnet test with –no-build so the step runs the compiled output instead of recompiling, plus a trx logger for results GitHub Actions can display or publishTestResults for Azure Pipelines. Coverage collection is the –collect flag. Both platforms attach the files to the run so reviewers see counts and failures inline.

What is a matrix build in CI/CD?

A strategy that expands one job definition into several runs over a grid of values, such as operating systems and target frameworks. Use it for libraries supporting multiple .NET versions or platforms. A single-target web API needs one Linux runner, and extra matrix legs cost minutes without adding information.

How should I version CI build artifacts?

Combine the version prefix in the project file with the pipeline’s run number as a build suffix, or cut releases from git tags for final versions. Put the run number in the artifact name too, so staging and production deployments reference distinguishable, traceable builds that map back to an exact commit.

The pipeline is the reviewer

Everything in this series ends here: the tests the pipeline runs, the artifact it builds, the migrations it applies before instances start, and the deployment it promotes. Treat the pipeline as the reviewer who sees every commit: pin what it uses, cache what it fetches, keep it fast, and never teach the team it can be argued with. If you deploy through containers, the image pipeline continues in the Docker guide’s build-and-push guide. If the fleet runs on Kubernetes, its GitOps guide picks up the manifest side. Every guide in this series lives on the .NET series index. The rule of thumb: if it is not built, tested, and shipped by the pipeline, it is not shipped by your team.

Last updated on 5 December 2026

Share this article

Leave a Reply

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