Black Friday40% OFFeverything + AI community $119/year · code BF26 · until Dec 1See all deals

.NET CI Quality Gates in GitHub Actions: Same Rules for Human and AI Pull Requests

Stefan ĐokićNov 30, 202616 min read.NET

Sponsored by Oracle

Five users report the same bug. One writes "session ends after a few minutes". Another gets "401 errors right after token refresh". A third keeps landing back on the sign-in page.

Search your tickets for "users keep getting logged out" with a classic LIKE query, and you get zero results.

I wanted to see how search by meaning handles this, so I built a small app with Oracle AI Database Free running in Docker.

The embedding model runs inside the database. My C# code just sends a string. One SQL query ranks tickets by meaning with VECTOR_DISTANCE and still applies a normal WHERE filter for product, status, and date.

LIKE found nothing. Search by meaning put the session timeout, the 401 and the sign-in redirect in the top 4.

Want to try it yourself? Oracle's free LiveLabs workshop walks you through creating embeddings and running similarity searches alongside relational queries. It takes about an hour.

Try the free LiveLabs workshop →

Want to reach thousands of .NET developers like this?

Sponsor TheCodeMan →

Keywords: .NET CI quality gates, GitHub Actions .NET, dotnet format verify-no-changes, dotnet format CI, warnings as errors CI, TreatWarningsAsErrors, Roslyn analyzers GitHub Actions, packages.lock.json, dotnet restore locked-mode, NU1004, NuGetAudit, NU1903, pragma warning disable, suppression gate, GitHub rulesets, required status checks, gitattributes line endings, AI agent pull requests, CLAUDE.md, setup-dotnet

What .NET CI Quality Gates Check

.NET CI quality gates are required checks that a pull request has to pass before it can be merged. I use three of them in GitHub Actions. format runs dotnet format --verify-no-changes. build-and-test builds in Release with analyzers and warnings as errors, then runs the unit and architecture tests. no-new-suppressions fails a pull request that adds a #pragma warning disable or any other way to switch a rule off. A ruleset on main makes all three required for every author, including AI agents.

A year ago I wrote Bullet-Proof .NET CI on GitHub. That workflow had one job that built with /warnaserror and verified formatting, with TreatWarningsAsErrors also set in Directory.Build.props. Nothing in it stopped a <NoWarn> in a project file, a #pragma, or a package version that changes between machines. For Module 09 of my Pragmatic .NET Code Rules course I rebuilt the pipeline to close those, and this post walks through it.

The sample is the Newsletter API from the course: Domain, Application, Infrastructure and Api projects, a unit test project and an architecture test project, on .NET 10. Every local output below comes from runs on .NET SDK 10.0.404 against the course repository at the Module 09 checkpoints.

CI Runs the Rules the Repository Already Has

By the time the course gets to CI, the rules already exist in the repository. The .editorconfig defines the code style. Directory.Build.props turns warnings into errors for every project:

TEXT
<PropertyGroup Label="Code Quality"> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AnalysisLevel>latest-recommended</AnalysisLevel> <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild> <GenerateDocumentationFile>true</GenerateDocumentationFile> <!-- We generate doc XML so IDE0005 (unused usings) works - but we don't require comments --> <NoWarn>$(NoWarn);CS1591</NoWarn></PropertyGroup>

Directory.Packages.props adds StyleCop, SonarAnalyzer and ReferenceTrimmer to every project with GlobalPackageReference, and the architecture test project has the 14 NetArchTest rules from my architecture tests issue.

All of that only works if someone runs the build before pushing. The pre-commit hook from earlier in the course can be skipped with git commit --no-verify, and a fresh clone doesn't install hooks at all. CI is the one place where the checks run on every pull request, and nobody can skip them.

The pipeline doesn't add new rules. It runs the same global.json, .editorconfig and props files on a clean Linux runner. If CI enforced a rule that the local build doesn't, people would only find out about it after they push.

.NET CI quality gates in GitHub Actions: a pull request runs the format, build-and-test and no-new-suppressions jobs, and the ruleset allows the merge only when all three are green

The GitHub Actions Workflow

This is the complete workflow, .github/workflows/quality.yml, at the end of Module 09:

YAML
name: quality on: pull_request: branches: [main] # labeled/unlabeled: adding suppression-approved must start a new run (a re-run reuses the old labels) types: [opened, synchronize, reopened, labeled, unlabeled] push: branches: [main] # A new push to the same PR cancels the old run - you only care about the latest commit.concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} permissions: contents: read env: DOTNET_NOLOGO: true DOTNET_CLI_TELEMETRY_OPTOUT: true jobs: format: name: format runs-on: ubuntu-latest steps: - uses: actions/checkout@v7  - uses: actions/setup-dotnet@v6 with: global-json-file: global.json cache: true cache-dependency-path: "**/packages.lock.json"  - name: Restore (locked) run: dotnet restore Newsletter.slnx --locked-mode  - name: Verify formatting run: dotnet format Newsletter.slnx --verify-no-changes --no-restore --verbosity normal  build-and-test: name: build-and-test runs-on: ubuntu-latest steps: - uses: actions/checkout@v7  - uses: actions/setup-dotnet@v6 with: global-json-file: global.json cache: true cache-dependency-path: "**/packages.lock.json"  # Locked mode: CI restores exactly what is in packages.lock.json, or fails (NU1004). # NuGetAudit runs here too - a vulnerable package is NU190x, an error with WAE. - name: Restore (locked) run: dotnet restore Newsletter.slnx --locked-mode  # Analyzers + code style (EnforceCodeStyleInBuild) run inside the build. # TreatWarningsAsErrors comes from Directory.Build.props - never override it here. - name: Build (Release) run: dotnet build Newsletter.slnx --configuration Release --no-restore  # Unit tests + architecture tests from Module 08 - name: Test run: > dotnet test Newsletter.slnx --configuration Release --no-build --logger trx --results-directory TestResults  - name: Upload test results if: always() uses: actions/upload-artifact@v7 with: name: test-results path: TestResults/*.trx  no-new-suppressions: name: no-new-suppressions if: github.event_name == 'pull_request' runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 with: fetch-depth: 0 # we diff against the base branch  - name: Check for new suppressions env: SUPPRESSION_APPROVED: ${{ contains(github.event.pull_request.labels.*.name, 'suppression-approved') }} run: bash scripts/check-suppressions.sh "origin/${{ github.base_ref }}"

It runs on every pull request to main and on every push to main. The concurrency block cancels the older run when someone pushes a new commit to the same pull request, and only for pull requests, so a run on main always finishes. permissions: contents: read is all the workflow needs, because it only reads the code.

Each job becomes one status check on the pull request, named after the job's name. I split the work into three jobs instead of one long job so the pull request shows which gate failed before anyone opens a log. The names also matter later, because the ruleset requires checks by name.

setup-dotnet doesn't get an SDK version in the workflow. It reads global.json, so the repository decides which SDK runs in CI:

JSON
{ "sdk": { "version": "10.0.100", "rollForward": "latestFeature" }}

Gate 1: dotnet format --verify-no-changes in CI

dotnet format --verify-no-changes doesn't write any files. It reports what it would change and exits with code 2, and a non-zero exit code fails the step. --no-restore skips a second restore, because the step before it already restored.

In the pull request from later in this post, two lines inside an endpoint are indented with six spaces instead of four. The format job reports them by file, line and column:

TEXT
Newsletter.Api/Program.cs(83,5): error WHITESPACE: Fix whitespace formatting. Delete 2 characters.Newsletter.Api/Program.cs(84,5): error WHITESPACE: Fix whitespace formatting. Delete 2 characters.

Line Endings Between Windows and the Linux Runner

The .editorconfig in this repository has end_of_line = lf. On Windows, depending on your git settings, files can be committed with CRLF line endings. Locally nothing complains. The Ubuntu runner checks out the files the way git stored them, and dotnet format reports every line of every such file. I converted one file to CRLF to show it:

TEXT
Newsletter.Domain/Services/EmailNormalizer.cs(1,50): error ENDOFLINE: Fix end of line marker. Replace 2 characters with '\n'.Newsletter.Domain/Services/EmailNormalizer.cs(2,35): error ENDOFLINE: Fix end of line marker. Replace 2 characters with '\n'.

The .editorconfig tells your editor which line endings to write. A .gitattributes file tells git which line endings to store:

TEXT
# Module 09: the CI runner is Linux. Store text files with LF, whatever OS you're on.* text=auto eol=lf # Windows-only scripts keep CRLF*.cmd text eol=crlf*.bat text eol=crlf

.gitattributes applies to files as they are added to git from now on. For the files already in the repository, run git add --renormalize . once and commit the result. In the course repository that commit touched 8 files that had been stored with CRLF. Make it its own commit, before the suppression gate below exists. I'll come back to why in that section.

Gate 2: Roslyn Analyzers and Warnings as Errors in CI

There is no separate analyzer step. Roslyn runs the analyzers while it compiles, so dotnet build runs the built-in CA and IDE rules, StyleCop, SonarAnalyzer and ReferenceTrimmer in one pass. With TreatWarningsAsErrors and EnforceCodeStyleInBuild in Directory.Build.props, a warning from any of them fails the build. The job builds in Release because that's the configuration that ships.

To see it fail, I added one unused variable to PublishArticleCommandHandler:

C#
var retries = 3;article.Publish();

One line, three errors from three analyzers:

TEXT
PublishArticleCommandHandler.cs(28,13): error CS0219: The variable 'retries' is assigned but its value is never usedPublishArticleCommandHandler.cs(28,13): error IDE0059: Unnecessary assignment of a value to 'retries'PublishArticleCommandHandler.cs(28,13): error S1481: Remove the unused local variable 'retries'.

The overlap is harmless here. If the same finding keeps showing up three times, pick one rule to own it and turn the other two off in .editorconfig.

setup-dotnet registers problem matchers for the build output, so on GitHub these errors also show up as annotations on the changed line in the pull request's Files changed tab. The reviewer sees the error next to the code without opening the log.

The test step uses --no-build, so it tests exactly what the build step produced. It runs the unit tests and the 14 architecture tests. --logger trx writes the results to a file, and the upload step has if: always(), so the results are uploaded when tests fail too.

Closing the Ways Around Warnings as Errors

Warnings as errors has been on since early in the course. CI is where the ways around it get closed. These are the usual ones:

  1. A flag on the build line. -p:TreatWarningsAsErrors=false in the workflow turns the rule off for every pull request.
  2. A project-level override. <NoWarn>, <WarningsNotAsErrors> or <TreatWarningsAsErrors>false</TreatWarningsAsErrors> in one project file, which few people read in review.
  3. #pragma warning disable around a piece of code.
  4. null! and #nullable disable. The first silences one nullable warning with one character, the second turns nullable analysis off for a whole file.
  5. A severity line in .editorconfig, which turns a rule off for the whole repository.

The course version of the gate didn't cover all of these. I found three holes while writing this post, more on them below.

The first one is easy to test. With an unused private method in the Domain, the normal build fails. With the flag, it passes:

BASH
dotnet build Newsletter.slnx -c Release --no-restore -p:TreatWarningsAsErrors=false
TEXT
EmailNormalizer.cs(15,27): warning S1144: Remove the unused private method 'RemoveDots'. 1 Warning(s) 0 Error(s)

That's why the build step in the workflow has the comment "never override it here". TreatWarningsAsErrors lives in Directory.Build.props, and the workflow doesn't pass /warnaserror or anything else that changes it. Local builds and CI builds read the same file.

The suppression gate handles the other four. Before that, two settings that keep CI and local builds on the same packages.

Lock Files and dotnet restore --locked-mode

global.json pins the SDK. For packages, NuGet picks the lowest version that satisfies each range, so most restores give the same result on every machine. They stop doing that with floating versions like 10.0.*, with a package source that has different versions than yours, or when a version gets unlisted or removed. A lock file records the exact resolved version of every package, direct and transitive, together with a hash of its content. Module 09 adds this group to Directory.Build.props:

TEXT
<PropertyGroup Label="Dependencies"> <!-- Module 09: same packages on every machine and in CI (restore with locked mode in CI) --> <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile> <!-- Module 09: vulnerable packages - direct AND transitive - are warnings, so errors with WAE --> <NuGetAudit>true</NuGetAudit> <NuGetAuditMode>all</NuGetAuditMode> <NuGetAuditLevel>low</NuGetAuditLevel></PropertyGroup>

After the next dotnet restore, every project has a packages.lock.json with each package's resolved version and content hash. Commit them. CI restores with --locked-mode, which restores exactly what the lock files say, or fails. I added a package without restoring, which is what happens when someone changes a package reference and doesn't commit the updated lock file:

BASH
dotnet add Newsletter.Api package Humanizer.Core --version 2.14.1 --no-restoredotnet restore Newsletter.slnx --locked-mode
TEXT
Newsletter.Api/Newsletter.Api.csproj : error NU1004: The package references have changed for net10.0. Lock file's package references: Microsoft.AspNetCore.OpenApi:[10.0.2, ), Microsoft.OpenApi:[2.7.5, ), ReferenceTrimmer:[3.5.9, ), SonarAnalyzer.CSharp:[10.9.0.115408, ), StyleCop.Analyzers:[1.2.0-beta.556, ), project's package references: Humanizer.Core >= 2.14.1, Microsoft.AspNetCore.OpenApi >= 10.0.2, ... The packages lock file is inconsistent with the project dependencies so restore can't be run in locked mode.

The lock files also make NuGet caching work. setup-dotnet with cache: true uses the lock files as the cache key and throws an error when it can't find one. cache-dependency-path: "**/packages.lock.json" is there because each project keeps its own lock file in its own folder.

NuGetAudit: Fail the Build on Vulnerable Packages

NuGetAudit checks packages against known vulnerabilities during restore and reports them as NU1901 to NU1904, from low to critical. NuGetAuditMode set to all includes transitive packages, so a vulnerable dependency of a dependency is reported too. For projects that target net10.0 that's already the default. The repository sets it explicitly so the behavior doesn't depend on the target framework. Because warnings are errors, a vulnerable package fails the restore:

BASH
dotnet add Newsletter.Api package Newtonsoft.Json --version 12.0.1
TEXT
error: NU1903: Warning As Error: Package 'Newtonsoft.Json' 12.0.1 has a known high severity vulnerability, https://github.com/advisories/GHSA-5crp-9r3c-p9vr

Nobody has to remember to run a separate security scan. It runs on every restore, locally and in both CI jobs.

Gate 3: Block New #pragma warning disable in Pull Requests

Sometimes a suppression is the right call, so the gate doesn't forbid them. It makes sure every new one is a decision a human saw. The script takes the diff between the pull request and the base branch, keeps only the added lines, and looks for the patterns:

BASH
#!/usr/bin/env bash# Module 09: fail a pull request that ADDS new diagnostic suppressions.# Existing suppressions are not touched - only lines added by this PR are checked.## Usage: scripts/check-suppressions.sh <base-ref> e.g. origin/main# Escape hatch: set SUPPRESSION_APPROVED=true (the workflow sets it when the PR has the# label "suppression-approved"), so a justified suppression is a visible, reviewed decision.set -euo pipefail base="${1:-origin/main}"pattern='#pragma warning disable|SuppressMessage|<NoWarn>|null!|#nullable disable|<Nullable>disable|<TreatWarningsAsErrors>false|<WarningsNotAsErrors>|severity *= *(none|silent|suggestion)' added=$(git diff --unified=0 "$base"...HEAD -- '*.cs' '*.csproj' '*.props' '*.targets' '*.editorconfig' '*.globalconfig' \ | grep -E '^\+[^+]' | grep -E "$pattern" || true) if [[ -z "$added" ]]; then echo "No new suppressions." exit 0fi echo "This pull request adds diagnostic suppressions:"echo "$added" if [[ "${SUPPRESSION_APPROVED:-false}" == "true" ]]; then echo "::warning title=Suppression approved::Label 'suppression-approved' is set - allowed." exit 0fi echo "::error title=New diagnostic suppression::Fix the code instead, or explain the suppression in the PR and add the label 'suppression-approved'."exit 1

It only checks added lines. A codebase with 50 existing suppressions doesn't fail on the first day. You clean those up on your own schedule, and no new ones get in.

The escape hatch is the suppression-approved label. With the label, the job passes and leaves a warning annotation:

TEXT
This pull request adds diagnostic suppressions:+#pragma warning disable S1144 // TODO: will be used for Gmail aliases later::warning title=Suppression approved::Label 'suppression-approved' is set - allowed.

Three details in the workflow make the job work:

  • if: github.event_name == 'pull_request', because a push to main has no base branch to compare against.
  • fetch-depth: 0 on the checkout. By default actions/checkout fetches one commit, and you can't diff against origin/main with one commit.
  • types: [opened, synchronize, reopened, labeled, unlabeled] on the trigger. Without labeled, adding the label doesn't start a new run. Re-running the old run doesn't help either, because a re-run uses the original event with the original labels.

Three Holes I Found While Writing This Post

The version of the script in the course repository scanned .cs, .csproj, .props and .targets files for the first four patterns. While testing for this post, I took the pull request from the next section, removed its #pragma, and tried three other ways to get the unused method or a nullable problem through.

A severity line in .editorconfig. One line in the [*.cs] section:

TEXT
[*.cs]dotnet_diagnostic.S1144.severity = none

The build passed with 0 warnings, dotnet format passed, all 15 tests passed, and the old script printed No new suppressions.. One line turned S1144 off for every C# file in the repository, and none of the three gates noticed. The section matters, too. When I first appended the line at the end of the file, it landed under the [*Tests/**.cs] section, applied only to test files, and the build still failed with S1144.

<TreatWarningsAsErrors>false</TreatWarningsAsErrors> in Newsletter.Domain.csproj. A project file is evaluated after Directory.Build.props, so this overrides it for one project. The build passed with S1144 as a warning, and the old script found nothing. This one didn't get through, though. The format job failed, because dotnet format --verify-no-changes runs the analyzers too, reported the S1144 warning, and exited with code 2.

#nullable disable. I added a Domain method that calls .Trim() on a string? parameter. With nullable enabled, the build fails with CS8602, "Dereference of a possibly null reference". With #nullable disable at the top of the file and the ? removed, the build had 0 warnings, format and tests passed, and the old script found nothing. This one got through all three gates.

The script above scans .editorconfig and .globalconfig files too, and adds patterns for severity downgrades, #nullable disable, <Nullable>disable, <TreatWarningsAsErrors>false and <WarningsNotAsErrors>. On the .editorconfig branch it fails with:

TEXT
This pull request adds diagnostic suppressions:+dotnet_diagnostic.S1144.severity = none::error title=New diagnostic suppression::Fix the code instead, or explain the suppression in the PR and add the label 'suppression-approved'.

The other two branches fail the same way, on + <TreatWarningsAsErrors>false</TreatWarningsAsErrors> and +#nullable disable. On the course history it stays quiet: every Module 09 checkpoint, the fixed teammate pull request and the agent's pull request from later in this post report No new suppressions..

A text search won't cover every way to switch a rule off. It makes the common ones need a label from a human, and when you find another way around it, you add a pattern.

Why the Line-Ending Commit Comes First

The script reads git diff, and renormalizing line endings rewrites every line of a file. I ran the script on the 09.01 commit, the one that only added the workflow and renormalized the 8 files. It failed on a suppression that had been in the repository for weeks:

TEXT
This pull request adds diagnostic suppressions:+ <NoWarn>$(NoWarn);CS1591</NoWarn>

The <NoWarn> line didn't change, only its line ending did, and the diff shows it as added. Renormalize first, in its own pull request, and approve that one with the label if the gate already exists.

A Pull Request That Fails All Three Gates

The course has a teammate pull request built for this module. It adds a GET /api/subscribers/count endpoint and a helper method for later:

In Program.cs:

TEXT
@@ -8,6 +8,7 @@+using Newsletter.Domain.Repositories;@@ -77,4 +78,10 @@+app.MapGet("/api/subscribers/count", async (ISubscriberRepository repository, CancellationToken cancellationToken) =>+{+ var subscribers = await repository.GetAllActiveAsync(cancellationToken);+ return Results.Ok(new { count = subscribers.Count });+});

In EmailNormalizer.cs:

TEXT
@@ -11,4 +11,11 @@+#pragma warning disable S1144 // TODO: will be used for Gmail aliases later+ private static string RemoveDots(string localPart)+ {+ return localPart.Replace(".", string.Empty, StringComparison.Ordinal);+ }+#pragma warning restore S1144

There are three problems in 14 added lines, and each gate catches a different one.

format fails on the indentation inside the endpoint, with the two WHITESPACE errors from earlier.

no-new-suppressions fails on the pragma:

TEXT
This pull request adds diagnostic suppressions:+#pragma warning disable S1144 // TODO: will be used for Gmail aliases later::error title=New diagnostic suppression::Fix the code instead, or explain the suppression in the PR and add the label 'suppression-approved'.

build-and-test fails, but not at the build step. The build reports 0 warnings and 0 errors, because the pragma silences S1144. The test step fails on the layer bypass rule from Module 08, because the endpoint injects a repository instead of going through an Application handler:

TEXT
Failed Newsletter.ArchitectureTests.LayerBypassTests.Api_Should_Not_Use_Repositories_Directly [82 ms]Error Message: Endpoints must go through an Application handler, never straight to a repository.Violating types: - Program

With only a build check, this pull request would be green. The pragma hides the analyzer warning, and an endpoint that skips the Application layer isn't something an analyzer looks for. Without the pragma, the same helper method fails the build:

TEXT
EmailNormalizer.cs(15,27): error S1144: Remove the unused private method 'RemoveDots'.

What each CI quality gate caught in the teammate pull request: format failed on indentation, no-new-suppressions failed on the pragma, the build was green because the pragma hid S1144, and the architecture test failed on the repository in the endpoint

The review fix removes the pragma and the unused method, and the endpoint calls the existing handler:

C#
app.MapGet("/api/subscribers/count", async (GetActiveSubscribersQueryHandler handler, CancellationToken cancellationToken) =>{ var subscribers = await handler.HandleAsync(cancellationToken); return Results.Ok(new { count = subscribers.Count });});

After the fix, dotnet format --verify-no-changes exits with 0, the script prints No new suppressions., the build has 0 warnings, and all 14 architecture tests and the unit test pass.

This post covers Module 09 (Integrating Code Quality into CI/CD) of my Pragmatic .NET Code Rules course. In the module I build this workflow lesson by lesson on a public demo repository, break each gate on camera, set up the ruleset, and have Claude Code open a pull request against it.

Required Status Checks With a GitHub Ruleset

A red check doesn't block anything by default. The merge button still works. A branch ruleset on main turns the checks into rules. In the repository, go to Settings, Rules, Rulesets, New branch ruleset, target the default branch, set enforcement to Active, and turn on:

  • Restrict deletions and Block force pushes.
  • Require a pull request before merging, so nobody pushes to main directly.
  • Require status checks to pass, with format, build-and-test and no-new-suppressions.
  • Require branches to be up to date before merging, so the checks ran against the code that lands.

Leave the bypass list empty, including for yourself, so the rules apply to admins too.

Rulesets are free on public repositories. On private repositories they need GitHub Pro, Team or Enterprise.

Three things to know about required checks before you set this up:

  • You can only pick a check that ran recently. A required status check has to have completed in the repository in the past seven days before it shows up in the list. Push the workflow and open one pull request first, because no-new-suppressions only runs on pull requests.
  • The check name is the job name. If someone renames a job, the ruleset keeps waiting for the old name, and every pull request shows "Expected - Waiting for status to be reported". Keep job names stable.
  • Don't add path filters to a required workflow. If a paths: or branches: filter skips the workflow, its checks stay pending and the pull request can't be merged. A job skipped by an if: condition is different: it reports as skipped, which GitHub counts as a success.

Same Gates for AI Agent Pull Requests

More and more pull requests are opened by Claude Code, the Copilot coding agent or another bot. Nothing in the workflow changes for them. The ruleset doesn't look at who opened the pull request. It needs a pull request, three green checks, and a person with merge rights to press the button.

When a check is red, an agent has the same shortcuts a person in a hurry has: commit with --no-verify, add a #pragma, edit the workflow, or re-run the job and hope. So the repository's CLAUDE.md, which already has the architecture rules from Module 08, gets a section about pull requests:

TEXT
## Pull requests - Every change goes through a pull request. CI must be green: `format`, `build-and-test`, `no-new-suppressions`.- Never commit with `--no-verify`, never push to `main`, never re-run CI hoping it passes.- If `no-new-suppressions` fails, remove the suppression and fix the code. Only a human adds the `suppression-approved` label.- When CI fails, read the failing job log, fix the cause, push again. Don't change the workflow to make it pass.

A red check with a file, a line and a rule ID is feedback an agent can act on. It reads the log, changes the code and pushes again.

In the last lesson of the module, Claude Code adds a GET /api/articles/count endpoint and opens the pull request with gh. Its commit adds a GetPublishedArticlesCountQueryHandler, a PublishedArticlesCountResponse record and a CountPublishedAsync method on the repository, and the endpoint calls the handler:

C#
app.MapGet("/api/articles/count", async (GetPublishedArticlesCountQueryHandler handler, CancellationToken cancellationToken) => Results.Ok(await handler.HandleAsync(cancellationToken)));

I ran the three gates on that commit again for this post: format clean, No new suppressions., 0 warnings, and all 15 tests passing.

One thing the ruleset doesn't cover by itself. For pull_request events, GitHub runs the workflow from the pull request's merge commit, so a pull request can change the workflow that checks it. Deleting a job doesn't get a pull request through, because the required check never reports and the merge stays blocked. Weakening a step does: remove --verify-no-changes from the format step, and the format check reports green. CLAUDE.md tells the agent not to touch the workflow. For a rule that holds no matter who opens the pull request, add a CODEOWNERS entry for .github/ and turn on "Require review from Code Owners" in the ruleset, so every change to the pipeline needs a review from the person who owns it.

FAQ

How do I run dotnet format in CI?

Run dotnet format with --verify-no-changes after a restore. It doesn't change any file, it exits with code 2 when a file would change, and the non-zero exit code fails the step. On a Linux runner, add a .gitattributes file with * text=auto eol=lf, otherwise files committed with CRLF on Windows fail with ENDOFLINE errors.

How do I run Roslyn analyzers in GitHub Actions?

Analyzers run inside dotnet build, so the build step is the analyzer step. Set TreatWarningsAsErrors, AnalysisLevel and EnforceCodeStyleInBuild in Directory.Build.props, and any analyzer warning fails the build locally and in CI. Don't pass /warnaserror or -p:TreatWarningsAsErrors=false in the workflow, keep the setting in the props file so both builds use the same rules.

What does dotnet restore --locked-mode do?

It restores exactly the package versions recorded in packages.lock.json and fails with NU1004 if the project's package references no longer match the lock file. It needs RestorePackagesWithLockFile set to true and the lock files committed to the repository.

How do I fail a .NET build on vulnerable NuGet packages?

Turn on NuGetAudit with NuGetAuditMode set to all and NuGetAuditLevel set to low. Restore reports known vulnerabilities as NU1901 to NU1904 warnings, for direct and transitive packages, and with TreatWarningsAsErrors those warnings fail the restore. Newtonsoft.Json 12.0.1, for example, fails with NU1903.

How do I block new #pragma warning disable lines in pull requests?

Add a CI job that diffs the pull request against the base branch and checks only the added lines for #pragma warning disable, SuppressMessage, <NoWarn>, null!, #nullable disable, project-level TreatWarningsAsErrors overrides and .editorconfig severity downgrades. Fail the job unless the pull request has a label that only a human adds. The checkout needs fetch-depth: 0, and the pull_request trigger needs the labeled and unlabeled types.

Why is my required status check stuck on Expected - Waiting for status to be reported?

The ruleset is waiting for a check name that never reports. Usually the job was renamed, or the workflow was skipped by a paths or branches filter. A job skipped by an if: condition reports as skipped, which GitHub counts as a success, so it doesn't block the merge.

Should pull requests from AI agents go through the same CI?

Yes, with the same required checks and a human who merges. Put the pull request rules in the agent's instructions file, and protect .github/workflows with CODEOWNERS, because a pull_request run uses the workflow file from the pull request itself.

Wrapping Up

.NET CI quality gates in GitHub Actions don't need new rules. They run the rules the repository already has on a machine nobody can configure by hand: dotnet format --verify-no-changes for style, a Release build for analyzers and warnings as errors, and dotnet test for the unit and architecture tests. Lock files and --locked-mode keep packages the same everywhere, NuGetAudit turns a vulnerable package into a build error, and the suppression gate makes every new #pragma, <NoWarn>, null!, #nullable disable or .editorconfig downgrade a decision someone approves. A ruleset with an empty bypass list makes all of it required, for people and for agents.

Break each gate once on purpose before you rely on it. That's how I found the .editorconfig line and the #nullable disable that got through all three.

For the basics, start with Bullet-Proof .NET CI on GitHub and Mastering Directory.Build.props. The architecture tests that run in the build-and-test job are in Architecture Tests in .NET: Test What the Compiler Can't See, and how CLAUDE.md and agent skills fit together is in .NET Skills for Coding Agents.

This post is based on Module 09 of Pragmatic .NET Code Rules. The course goes through the full setup step by step: EditorConfig, analyzers, Directory.Build.props, project cleanup, architecture tests, and this pipeline.

That's all from me today.

Stefan Đokić
About the author

Stefan Đokić

Microsoft MVP and senior .NET engineer with extensive experience designing enterprise-grade systems and teaching architectural best practices.

Every Monday · Free

One practical .NET & architecture tip, every Monday.

Join 25,000+ engineers who improve their C# skills in a 5-minute read.

No spam. Unsubscribe anytime.