Maxbeauchemin.Api.Interceptor 1.5.0

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

api-interceptor

The Maxbeauchemin.Api.Interceptor Nuget package allows you to create scenarios where your incoming API calls will be intercepted to help simulate outages or mock different behavior.

This package can be used to help test different error-states applications integrating with your code may be expected to endure.

Usage

The main content of the package is the ApiInterceptorFilterAttribute

To enable the interceptor, you must either manually add the attribute to all the different API controllers that you want to be able to intercept using the [ApiInterceptorFilterAttribute(..)] syntax, or set it up globally (recommended)

For global setup, you can use the following syntax:

var filter = new ApiInterceptorFilterAttribute(apiInterceptorOptions, identityProvider);

filter.Order = int.MinValue;
    
builder.Services.AddMvc(opts =>
{
    opts.Filters.Add(filter);
});

If you plan on filtering any endpoints by their Body, you will need to enable Request Buffering

The following code should be added in your Program.cs before your UseEndpoints / MapControllers

app.Use(next => context =>
{
    if (context.Request.ContentType != null && 
        context.Request.ContentType.StartsWith("application/json", StringComparison.InvariantCultureIgnoreCase))
    {
        context.Request.EnableBuffering();
    }

    context.Request.EnableBuffering();
    return next(context);
});

Failing to do this step will result in the ActionFilter always reading the Request Body as an empty string

For the API Interception to work, you will need to create either an Options object, or a function that can be used to retrieve them when necessary.

The Options object configures the functionality of the interceptor and the different scenarios that it should be setup to handle. If you wish to be able to switch the options without having to restart your application, you will need to construct the class using an Options Provider function that can be used to retrieve the current setup.

You can optionally provide an Identity Provider which converts an ActionExecutingContext into a String identifying a specific actor. This would normally be used to extract user-identity information from an API token, but is left flexible for your implementation.

Here's an example of an Identity Provider which would get identity information from an API header:

var identityProvider = (ActionExecutingContext ctx) =>
{
    var identityHeader = ctx.HttpContext.Request.Headers.FirstOrDefault(h => h.Key == "X-Identity");

    return identityHeader.Value.ToString();
};

If the Options Provider / Identity Provider / Logger aren't able to be set at program startup, you can swap them out later using their respective Set functions, as long as you maintain a reference to the Filter class you initialized.

Options

This section describes the different parameters that can be provided in the Options objects to control the Api Interceptor functionality

  • Enabled (bool req.) - whether the API interceptor should be enabled
  • Scenarios (array req.) - the list of scenarios that should be handled. The order listed is the order they will be checked in. The first matching scenario for a request is the only one that will be used (if any).
    • Name (string req.) - name of the scenario, will be attached as an X-Api-Interceptor-Scenario response header and used for Warning Logs
    • Enabled (bool req.) - whether this individual scenario should be checked
    • DisableWarningLog (bool opt.) - whether Warning logs should be disabled. Default is all interceptions record warning logs.
    • Filter (object req.) - the criteria that will be used to identify if a particular request should be intercepted by this scenario
      • Identities (string array opt.) - if provided, only identities (obtained from the identity provider) that are in the list will be intercepted
      • Endpoints (array opt.) - if provided, only APIs that match one of the items in this collection will be intercepted
        • MethodType (string req.) - type of method to match, can be wild-carded with *
        • URL (string req.) - URL to match, can be partial, or can be wild-carded with *
        • Parameters (array opt.) - query parameters to match, each key can have multiple values to attempt to match to, but the request must contain a match in each key
          • Key (string req.) - the parameter name that must be provided
          • Values (string array req.) - the list of values that can be matched for this parameter
        • BodyProperties (array opt.) - query parameters to match, each key can have multiple values to attempt to match to, but the request must contain a match in each key
          • Path (string req.) - the JSON path to attempt to match, additional details in the Json Path section below
          • Values (string array req.) - the list of values that can be matched for this property
      • Percentage (int opt.) - if provided, a random integer between 1 and 100 will be chosen, and the request will only be intercepted if the number is lower than this parameter's value
    • Actions (object req.) - the action(s) that will be performed if this scenario intercepts a request
      • DelayMs (int opt.) - if provided, a delay of the provided Milliseconds will be added before proceeding like normal
      • RespondWith (object opt.) - if provided, the normal underlying code will be skipped and this is the response that will be returned instead.
        • HttpCode (int req.) - the HTTP Status Code identifier to respond with
        • Body (object opt.) - if provided, this is the body that will be in the response. Defaults to {}

Json Path

For Body filtering, we allow you to specify one or more Json Paths that must match a provided value. The path follows the correct pattern, as defined in RFC 9535

Here are a few examples you can use - note that not all the JSONPath functionality (like range matching) may work at this time

  • $.X: X property at root of object
  • $.X.Y: Y property inside the X object
  • $[0]: value in the first position of the root array
  • $[*]: value at any position of the root array
  • $[1].Z: Z property of object at 2nd position of the root array
  • $[*].Z: Z property of object at any position of the root array
  • $.X[2]: value in the third position of the X array
  • $[*][3]: value in the fourth position of any positions of the root array
  • $[*][*]: value in any position of any positions of the root array

You can test your path at this handy website - jsonpath.com

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

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.5.0 8,065 10/11/2024
1.4.0 109 10/7/2024
1.3.0 2,414 10/4/2024
1.2.0 455 9/3/2024
1.1.0 146 9/3/2024
1.0.0 157 8/31/2024 1.0.0 is deprecated because it is no longer maintained.