ApiGuardrails.AspNetCore 1.1.0

dotnet add package ApiGuardrails.AspNetCore --version 1.1.0
                    
NuGet\Install-Package ApiGuardrails.AspNetCore -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ApiGuardrails.AspNetCore" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ApiGuardrails.AspNetCore" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="ApiGuardrails.AspNetCore" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ApiGuardrails.AspNetCore --version 1.1.0
                    
#r "nuget: ApiGuardrails.AspNetCore, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package ApiGuardrails.AspNetCore@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=ApiGuardrails.AspNetCore&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=ApiGuardrails.AspNetCore&version=1.1.0
                    
Install as a Cake Tool

๐Ÿ›ก๏ธ ApiGuardrails for ASP.NET Core

NuGet Version .NET License: MIT

A developer-first API quality, safety, and governance toolkit for ASP.NET Core.

In distributed microservice and modular web API architectures, different teams inevitably introduce subtle inconsistencies: divergent error payloads, missing Correlation IDs, unpaginated collection queries, missing rate-limiting policies, unannounced API deprecations, and loose security headers.

ApiGuardrails provides a unified, configurable rule engine for ASP.NET Core that enables engineering teams to define standards, inspect violations via live dashboards and OpenTelemetry metrics, and safely enforce contracts.


โšก Quickstart

1. Install the NuGet Package

dotnet add package ApiGuardrails.AspNetCore

2. Configure in Program.cs

using ApiGuardrails.AspNetCore;
using ApiGuardrails.Core;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

// Register ApiGuardrails with options
builder.Services.AddApiGuardrails(options =>
{
    // Adoption mode: ReportOnly (default - zero disruption), Enforce, or Disabled
    options.Mode = GuardrailMode.ReportOnly;

    // Automatic traceability & security
    options.CorrelationIdHeader = "X-Correlation-Id";
    options.AutoAttachCorrelationId = true;
    options.AutoAttachSecurityHeaders = true;
    options.AutoAttachDeprecationHeaders = true;

    // Optional: add a callback for alerts or external log forwarders
    options.OnViolationDetected = violation =>
    {
        Console.WriteLine($"[ApiGuardrail] {violation}");
    };
});

builder.Services.AddProblemDetails();

WebApplication app = builder.Build();

// Enable ApiGuardrails middleware in request pipeline
app.UseApiGuardrails();

// Compliant collection endpoint with pagination policy (AG1007)
app.MapGet("/api/products", (int? page, int? pageSize) =>
{
    return Results.Ok(new[] { new { Id = 1, Name = "Sensor" } });
})
.WithSummary("List products")
.WithDescription("Retrieves paginated products catalog.")
.WithPaginationPolicy(maxPageSize: 100, defaultPageSize: 20);

// Map live diagnostics endpoints
app.MapApiGuardrailsDashboard("/_guardrails/dashboard"); // Interactive HTML dashboard
app.MapApiGuardrailsReport("/_guardrails/violations");   // JSON telemetry
app.MapApiGuardrailsSarifReport("/_guardrails/sarif");   // SARIF 2.1.0 for CI/CD Code Scanning
app.MapApiGuardrailsMarkdownReport("/_guardrails/markdown"); // GitHub Actions summary

app.Run();

๐Ÿ“‹ Standard Rules Catalog

Rule ID Name Stage Default Severity Description
AG1001 Required Endpoint Metadata Startup Warning Ensures endpoints declare summary or description for OpenAPI discoverability. Automatically skips endpoints marked with .ExcludeFromDescription().
AG1002 Configured Request-Size Policy Startup, Request Warning / Error Verifies endpoints accepting request bodies declare explicit [RequestSizeLimit] policies, and blocks oversized requests (HTTP 413).
AG1003 Standard Error-Response Convention Startup, Response Warning Enforces standard RFC 7807/9457 ProblemDetails (application/problem+json) across all 4xx/5xx responses.
AG1004 Required Response Metadata Response Warning Guarantees distributed traceability by attaching correlation headers (X-Correlation-Id, traceparent).
AG1005 Endpoint Convention Violations Startup Warning Enforces RESTful URI design: lowercase kebab-case route segments, no trailing slashes, and explicit HTTP verbs.
AG1006 Rule Configuration Validity Startup Error Validates configuration integrity and flags conflicting rule switches at startup.
AG1007 Mandatory Pagination Policy Startup, Request Warning / Error Detects unbounded collection endpoints at startup; blocks requests requesting excessive page sizes (HTTP 400).
AG1008 API Deprecation Standards Startup, Response Info / Warning Implements RFC 8594 standard deprecation. Automatically attaches Deprecation, Sunset, and Link headers.
AG1009 Defensive Security Headers Response Warning Enforces defensive headers (X-Content-Type-Options: nosniff, X-Frame-Options: DENY) on all API responses.
AG1010 Rate Limiting Policy Startup Warning Validates that mutating (POST/PUT/DELETE/PATCH) and sensitive routes declare rate limiting policies.
AG1011 Content Negotiation & Media Types Request Warning / Error Enforces standard JSON payloads and valid Content-Type and Accept media types.

๐ŸŽฏ Per-Endpoint Rule Suppression ([SkipGuardrail])

When a specific endpoint has legitimate architectural reasons to bypass a guardrail (e.g. an internal webhook, an unpaginated enum lookup, or a legacy route), bypass it cleanly without disabling the rule globally:

Minimal APIs:

app.MapGet("/api/legacy-route/", () => Results.Ok())
    .SkipGuardrail(RuleIds.EndpointNamingConventions, RuleIds.RequiredEndpointMetadata);

Controllers:

[ApiController]
[Route("api/[controller]")]
public class InternalWebhooksController : ControllerBase
{
    [HttpPost("events")]
    [SkipGuardrail(RuleIds.RequestSizePolicy, RuleIds.RateLimitingPolicy)]
    public IActionResult ReceiveEvent() => Ok();
}

๐Ÿ“Š Interactive HTML Dashboard

Access GET /_guardrails/dashboard for a live, responsive, dark/light theme embedded dashboard:

  • Compliance Score: Real-time compliance percentage gauge.
  • Metric Cards: Total violations, Error count, Warning count, Info count.
  • Interactive Filtering & Search: Instant filtering by severity and route substring.
  • Actionable Remediation: Exact fix instructions for every detected violation.
  • Zero External CDNs: Self-contained CSS and JavaScript โ€” operates securely in air-gapped environments.

๐Ÿš€ DevSecOps & CI/CD Integration (SARIF & Markdown)

GitHub Code Scanning & Azure DevOps (SARIF 2.1.0)

Map the SARIF endpoint to publish violations directly into your CI pipeline:

app.MapApiGuardrailsSarifReport("/_guardrails/sarif");

In your GitHub Actions workflow:

- name: Export Guardrail Violations
  run: curl http://localhost:5000/_guardrails/sarif -o guardrails.sarif

- name: Upload SARIF to GitHub Code Scanning
  uses: github/codeql-action/upload-sarif@v3
  with:
    sarif_file: guardrails.sarif

GitHub Actions Step Summaries (Markdown)

app.MapApiGuardrailsMarkdownReport("/_guardrails/markdown");

๐Ÿฉบ ASP.NET Core Health Checks Integration

Integrate ApiGuardrails with native ASP.NET Core Health Checks (/health):

builder.Services.AddHealthChecks()
    .AddApiGuardrailsHealthCheck();
  • Returns Healthy when all endpoints comply.
  • Returns Degraded when warnings or non-blocking issues exist.
  • Returns Unhealthy when critical errors are detected in Enforce mode.

๐Ÿงช Testing Toolkit (ApiGuardrails.Testing)

Validate guardrail compliance in unit and integration test suites:

dotnet add package ApiGuardrails.Testing
[Fact]
public async Task AllEndpoints_ComplyWithGuardrails()
{
    using var app = new WebApplicationFactory<Program>();
    
    // Scans all registered endpoints at startup and fails if violations exist
    await app.Services.AssertNoViolationsAsync(minimumSeverity: RuleSeverity.Warning);
}

[Fact]
public async Task Response_HasSecurityAndTraceabilityHeaders()
{
    using var app = new WebApplicationFactory<Program>();
    var client = app.CreateClient();

    var response = await client.GetAsync("/api/products");
    
    response.AssertHasCorrelationId();
    response.AssertHasSecurityHeaders();
}

โš™๏ธ Adoption Modes

Mode Behavior Recommended Use
GuardrailMode.ReportOnly (Default) Evaluates rules, logs structured telemetry, populates violation store and dashboard without disrupting traffic. Production rollout, legacy codebases, quality monitoring.
GuardrailMode.Enforce Blocks non-compliant requests (HTTP 400/413/415 with RFC 7807 ProblemDetails) and halts startup on critical errors. New services, staging/QA environments, strict governance.
GuardrailMode.Disabled Bypasses all evaluations with zero overhead. Emergency rollback or performance benchmarking.

๐Ÿ“„ License

This project is licensed under the MIT License.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 101 11/13/2026
1.0.0 121 10/15/2026

v1.1.0 Release:
- Five new standard guardrails:
 - AG1007: Mandatory Pagination Policy (detects unbounded queries and enforces safe page sizes)
 - AG1008: API Deprecation Standards (RFC 8594 Deprecation/Sunset headers)
 - AG1009: Defensive Security Headers (X-Content-Type-Options: nosniff, X-Frame-Options: DENY)
 - AG1010: Rate Limiting Policy (ensures mutating/sensitive routes declare rate limits)
 - AG1011: Content Negotiation and Media Type Validation
- Granular per-endpoint rule suppression via [SkipGuardrail] and .SkipGuardrail()
- Embedded interactive HTML status dashboard via MapApiGuardrailsDashboard()
- CI/CD SARIF 2.1.0 exporter for GitHub Code Scanning via MapApiGuardrailsSarifReport()
- Markdown summary generator via MapApiGuardrailsMarkdownReport()
- ASP.NET Core Health Checks integration via AddApiGuardrailsHealthCheck()
- Minimal API route-group filter support via AddApiGuardrailsFilter()