MockResponse.Middleware.Core 8.0.1

dotnet add package MockResponse.Middleware.Core --version 8.0.1
                    
NuGet\Install-Package MockResponse.Middleware.Core -Version 8.0.1
                    
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="MockResponse.Middleware.Core" Version="8.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MockResponse.Middleware.Core" Version="8.0.1" />
                    
Directory.Packages.props
<PackageReference Include="MockResponse.Middleware.Core" />
                    
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 MockResponse.Middleware.Core --version 8.0.1
                    
#r "nuget: MockResponse.Middleware.Core, 8.0.1"
                    
#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 MockResponse.Middleware.Core@8.0.1
                    
#: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=MockResponse.Middleware.Core&version=8.0.1
                    
Install as a Cake Addin
#tool nuget:?package=MockResponse.Middleware.Core&version=8.0.1
                    
Install as a Cake Tool

<a id="readme-top"></a>

MockResponse.Middleware.Core

.NET License

CI/CD Pipeline CodeQL NuGet - Core

This package provides the core abstractions, middleware, and configuration models used by MockResponse.Middleware.

It defines shared interfaces, options models, resolution strategies, and the base middleware pipeline that provider-specific implementations (e.g. Azure Blob Storage, Local Folder Store, or your own) can plug into.

Table of Contents

๐Ÿ“ฆ Installation

dotnet add package MockResponse.Middleware.Core

<p align="right">(<a href="#readme-top">back to top</a>)</p>

๐Ÿšฆ Intended Usage

This package is not intended to be used directly. Instead, install one of the following provider packages based on your needs:

๐Ÿ”ง Create Your Own Provider

If neither built-in provider suits your scenario, you can create a custom one by following these steps:

  1. Create a new class library, e.g. MockResponse.Middleware.CustomType

  2. Reference dependencies

<PackageReference Include="MockResponse.Middleware.Core" Version="x.y.z" />
<PackageReference Include="Microsoft.Extensions.Options" Version="x.y.z" />
  1. Define your options
public record CustomProviderOptions : IProviderOptions
{
	public static string SectionName => nameof(CustomProviderOptions);

	[Required]
	public string SomeSetting { get; set; } = default!;
}
  1. Implement the provider
internal sealed class CustomResponseProvider : IMockResponseProvider, IMockResponseProviderDefinition
{
	public static string ProviderName => "CustomProvider";
	public string Name => ProviderName;
	private readonly CustomProviderOptions _options;
	
	public CustomResponseProvider(IOptionsMonitor<CustomProviderOptions> opts)
	{
		_options = opts.CurrentValue;
	}

	public Task<(string Response, string ProviderName)> GetMockResponseAsync(string identifier)
	{
		// this is where are the logic happens...
		return Task.FromResult(("{\"ok\":true}", Name));
	}
}
  1. Register your provider
services.AddApiMocking(Configuration)
	.AddStore<CustomProviderOptions, CustomResponseProvider>(CustomResponseProvider.Name);

<p align="right">(<a href="#readme-top">back to top</a>)</p>

โœจ Features

  • Core middleware pipeline for injecting mock responses
  • Pluggable provider model via IMockResponseProvider
  • Support for:
    • path exclusion
    • Metadata resolution from endpoint definitions
    • Flexible configuration via IOptionsMonitor<T>

<p align="right">(<a href="#readme-top">back to top</a>)</p>

๐Ÿ”— Mock Resolution Strategy

The mock resolution process is driven by the matched endpoint, response metadata, and request headers. Here's how it works:

How Mapping Works

Mock responses are resolved using a combination of the request's route (via endpoint metadata), response status code, and an optional variant header.

Each route endpoint that uses .Produces<T>() defines a C# type (T) that becomes part of the lookup key in MockOptions:ResponseMappings.

Note: By default, if no status is passed to .Produces<T>(), it defaults to 200 OK.

200 OK

.Produces<WeatherForecast>();

201 Created

.Produces<WeatherForecast>(StatusCodes.Status201Created);
Mapping Format
  "<Namespace>.<ClassName>[.<X-Mock-Variant>]":"<Identifier>"
  • <Namespace>.<ClassName>: The fully qualified name of the response model (from .Produces<T>())
  • <X-Mock-Variant>: (Optional) Custom variant passed in the X-Mock-Variant header
  • <Identifier>: The value passed to the mock provider (this might be a file name, blob name, database key, etc)

Note: If no X-Mock-Variant header is provided, the middleware will look for a mapping using just the fully qualified type name.

Examples
Without Variant

For this endpoint:

app.MapGet("/weatherforecast", () => ...).Produces<WeatherForecast>();

And this request:

GET /weatherforecast
  X-Mock-Status: 200

The middleware matches:

  • The /weatherforecast route โ†’ associated endpoint
  • The declared response type for status 200 โ†’ Your.Namespace.WeatherForecast
  • The following mapping:
"ResponseMappings": {
  "Your.Namespace.WeatherForecast": "WeatherForecast.json"
}

โœ… If found, it returns the content from WeatherForecast.json (or whatever identifier is needed by the provider)

โŒ If not found, a 404 Not Found is returned

Note: If no .Produces<T>(<StatusCode>) exists for the given status, the system cannot infer the appropriate mock response type and will return an error.

With Variant

Using the same endpoint above, but with:

GET /weatherforecast
  X-Mock-Status: 200
  X-Mock-Variant: Freezing

The middleware appends the response type variant (Freezing) to the fully qualified class name:

Your.Namespace.WeatherForecast.Freezing

And looks for a match in:

"ResponseMappings": {
  "Your.Namespace.WeatherForecast.Freezing": "WeatherForecast.Freezing.json"
}

โœ… If found, it returns the mock for the variant

โŒ If not, a 404 is returned with an error explaining the missing mapping

<p align="right">(<a href="#readme-top">back to top</a>)</p>

โš™๏ธ MockOptions Configuration

The MockOptions class defines middleware behavior and is bound from the MockOptions section of your configuration (e.g. appsettings.json or User Secrets).

Structure

{
  "MockOptions": {
    "ExcludedRequestPaths": [ "/api/health", "/openapi", "/metrics", "/redoc", "/swagger" ],
    "ResponseMappings": {
      "Some.Namespace.WeatherForecast": "WeatherForecast.json",
      "Some.Namespace.WeatherForecast.Freezing": "subfolder/WeatherForecast.Freezing.json"
    },
    "UseMock": true
  }
}

๐Ÿ”ง These options are bound via services.Configure<MockOptions>() as part of AddApiMocking(...) setup and can be accessed through IOptionsMonitor<MockOptions> if needed for advanced scenarios.

Description of Properties

Property Type Description Default
UseMock bool Enables or disables mocking. When true, matching requests will return mock responses instead of reaching real endpoints. false
ExcludedRequestPaths string[] Optional list of path relatives to bypass mock resolution. Useful for excluding routes like health checks, OpenAPI docs, or metrics endpoints. [] (empty)
ResponseMappings Dictionary<string,string> Maps fully qualified response type names (optionally including variants) to identifiers (like filenames or blob keys) used by the selected provider. Case-insensitive. {}

โ„น๏ธ Response type keys in ResponseMappings must match the fully qualified type name declared in .Produces<T>(). Casing is ignored.

For full property definitions, see MockOptions.

<p align="right">(<a href="#readme-top">back to top</a>)</p>

๐Ÿงช Troubleshooting

400 Bad Request

โš ๏ธ Missing required 'X-Mock-Status' header

Make sure the request includes the X-Mock-Status header with a valid integer value.

โš ๏ธ '"200"' is not a valid StatusCode

Ensure you are passing a valid integer (200) in the X-Mock-Status header...not a string "200".

404 Not Found

โš ๏ธ Metadata not found

Error Message

No [400] status code metadata was found for endpoint [HTTP: GET /weatherforecast]

Cause

The endpoint does not define .Produces<T>() for the given status code.

Solution

Add .Produces<T>(StatusCodes.Status400BadRequest) to the route definition (or whatever status code you were trying to use).

โš ๏ธ Mock not defined

Error Message

No [200] status code mapping was found for [HTTP: GET /weatherforecast] and variant [Inferno]

Cause

The middleware found metadata for the status code, but no mapping exists for the resolved response type and variant.

Solution

Ensure MockOptions:ResponseMappings contains a mapping for the full key. For example:

"ResponseMappings": {
  "MockResponse.Middleware.Example.LocalFolder.Models.WeatherForecast.Inferno": "WeatherForecast.Inferno.json"
}

Double-check that the key name matches exactly, including casing and variant.

<p align="right">(<a href="#readme-top">back to top</a>)</p>

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  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.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on MockResponse.Middleware.Core:

Package Downloads
MockResponse.Middleware.Azure.BlobStorage

Mock response provider using Azure Blob Storage

MockResponse.Middleware.LocalFolderStore

Mock response provider using local folder storage

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
8.0.1 97 7/29/2025
8.0.1-preview 117 6/26/2025