How to Implement API Contract Testing in ASP.NET Core 10 Using Pact and C# (2026)

The inventory endpoint still responds with HTTP 200, but its new response calls the stock count quantity. The storefront deserializes the old available field and shows zero. A consumer-driven Pact test makes that dependency visible: exercise the consumer against a mock, record what it needs, then replay the contract against a real ASP.NET Core provider.

What should a consumer contract cover?

Capture the parts of an interaction that the consumer relies on: method, path, required headers, expected status, and the fields it actually reads. Pact does not prove that a database is healthy, verify authorization comprehensively, or replace an end-to-end smoke test. A contract should be strict enough to catch breaking changes while allowing provider changes the consumer can safely ignore.

Consumer tests record an HTTP pact that the provider verifies over a real network endpoint.
Consumer tests record an HTTP pact that the provider verifies over a real network endpoint.
Test Primary question
Consumer unit test Does our client logic handle this input?
Pact consumer + provider verification Can both parties still exchange the messages the consumer relies on?
End-to-end test Does a deployed workflow work with actual configuration and dependencies?

Create the provider and test projects

Use the .NET 10 SDK, a shell, and a platform supported by the PactNet native library. This guide uses Pact Specification v4 and PactNet major version 5. The sample has two sibling directories, with InventoryApi/Program.cs and Inventory.Contracts/InventoryContractTests.cs.

BASH
dotnet new web -n InventoryApi -f net10.0
dotnet new xunit -n Inventory.Contracts -f net10.0
dotnet add Inventory.Contracts package PactNet --version '5.*'

Replace InventoryApi/Program.cs with the following endpoint. A known fixture replaces the database so the provider can verify a stable interaction.

Program.cs
var app = WebApplication.CreateBuilder(args).Build();
app.MapGet("/inventory/{sku}", (string sku) => sku == "MUG-1"
    ? Results.Ok(new { sku = "MUG-1", available = 4 })
    : Results.NotFound());
app.Run();

Write the consumer and provider tests

Remove the generated sample test and add this file to Inventory.Contracts. In a product repository, move InventoryClient into the consumer project, reference that project in tests, and test the same client used in production. Avoid duplicating its serialization behavior in test-only code.

InventoryContractTests.cs
using System.Net;
using System.Net.Http.Json;
using PactNet;
using PactNet.Verifier;
using Xunit;

public sealed class InventoryContractTests
{
    private const string Consumer = "Storefront";
    private const string Provider = "Inventory API";
    private static string DirectoryPath =>
        Environment.GetEnvironmentVariable("PACT_DIR")
        ?? Path.Combine(AppContext.BaseDirectory, "pacts");

    [Fact]
    public async Task Consumer_can_read_availability()
    {
        var pact = Pact.V4(Consumer, Provider, new PactConfig
        {
            PactDir = DirectoryPath
        }).WithHttpInteractions();
        pact.UponReceiving("the Storefront requests stock for MUG-1")
            .WithRequest(HttpMethod.Get, "/inventory/MUG-1")
            .WillRespond()
            .WithStatus(HttpStatusCode.OK)
            .WithJsonBody(new { sku = "MUG-1", available = 4 });

        await pact.VerifyAsync(async context =>
        {
            using var http = new HttpClient { BaseAddress = context.MockServerUri };
            var inventory = new InventoryClient(http);
            var stock = await inventory.GetAsync("MUG-1");
            Assert.Equal("MUG-1", stock.Sku);
            Assert.Equal(4, stock.Available);
        });
    }

    [Fact]
    public void Provider_serves_the_contract()
    {
        var baseUrl = Environment.GetEnvironmentVariable("PROVIDER_URL")
            ?? "http://127.0.0.1:5083";
        using var verifier = new PactVerifier(Provider, new PactVerifierConfig());
        verifier.WithHttpEndpoint(new Uri(baseUrl))
            .WithFileSource(new FileInfo(Path.Combine(DirectoryPath, $"{Consumer}-{Provider}.json")))
            .Verify();
    }
}

public sealed class InventoryClient(HttpClient http)
{
    public async Task<Stock> GetAsync(string sku, CancellationToken ct = default) =>
        await http.GetFromJsonAsync<Stock>($"inventory/{Uri.EscapeDataString(sku)}", ct)
        ?? throw new InvalidOperationException("Expected an inventory document.");
}
public sealed record Stock(string Sku, int Available);

The consumer test sends a real HTTP request to Pact’s mock server. Pact records the interaction only after the request and expectations are satisfied. The provider verifier later reads the contract from disk and calls the API via TCP. Use Kestrel for that step. PactNet’s native verifier cannot reach an in-memory ASP.NET Core TestServer.

Run a contract and prove it catches a regression

Start the provider in one terminal. Use a loopback port and point the verifier at a different port through PROVIDER_URL if needed.

BASH
dotnet run --project InventoryApi --no-launch-profile \
  --urls http://127.0.0.1:5083

In another terminal, run the tests in this order. The consumer writes the Pact JSON before the provider reads it. Use a clean pact directory on each CI run.

BASH
export PACT_DIR="$PWD/pacts"
dotnet test Inventory.Contracts --filter FullyQualifiedName~Consumer_can
dotnet test Inventory.Contracts --filter FullyQualifiedName~Provider_serves

Expected outcome: one successful test per command. To verify a negative case, rename available to quantity on the provider, restart it and rerun provider verification. The existing pact should fail because its required response field is absent. Restore the original field or introduce a compatible migration and rerun.

Move to separate repositories and CI

Generate pacts in the consumer pipeline and publish them to a Pact Broker or a trusted build artifact store. Attach immutable application versions, such as a commit SHA, and record branch/environment separately. Verify provider builds against supported consumers and publish results under the provider version. Ask the broker’s deployment check about a target version and environment before releasing. A contract artifact alone tells you what was expected, while verification records whether a specific build could serve it.

Where a fixture must vary by interaction, use provider states. Make test-only setup idempotent and restrict it to isolated environments. Never point a provider-state endpoint at production data. Avoid putting credentials, real customer records or bearer tokens in pacts and broker logs. Add authorization and timeout cases if the consumer has meaningful behavior for those outcomes.

How strict should a body match be?

Use exact values when the value itself matters, such as an enum that controls a branch. Use matchers for generated IDs or numeric fields when the consumer cares about their type. A test fixture should exercise the consumer’s real parsing logic.

Why does provider verification say connection refused?

Confirm that the process is listening on the URL used by the verifier. In CI, add a readiness check before running verification and ensure the verifier can reach the provider’s network namespace.

Design a contract suite teams can maintain

Write one contract per interaction that changes the consumer’s behavior. A storefront might need 404 to distinguish an unknown SKU from out-of-stock inventory, while another client might treat both as unavailable. Capture that behavior where it matters. If a consumer never reads an optional description, leave it out of the contract to give the provider room to evolve. Give each interaction a descriptive name tied to the client workflow.

Use explicit provider fixtures for difficult scenarios, such as a SKU that exists but is restricted to one tenant. The fixture should create the relevant state idempotently and clean it up or use isolated storage. Separate contract credentials from production identity. Add a smoke test against the deployed system for dependencies Pact does not exercise, including DNS and certificates.

When a field has to change, add the new field alongside the existing one and publish a provider build that verifies against both supported contracts. Deploy consumer changes and keep the old field until the deployment matrix shows the old contract is no longer needed. The broker gives teams evidence for this decision, while their policy determines how long older clients remain supported.

References and related reading

Comments