AJP.MediatrEndpoints 1.4.1

dotnet add package AJP.MediatrEndpoints --version 1.4.1                
NuGet\Install-Package AJP.MediatrEndpoints -Version 1.4.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="AJP.MediatrEndpoints" Version="1.4.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add AJP.MediatrEndpoints --version 1.4.1                
#r "nuget: AJP.MediatrEndpoints, 1.4.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.
// Install AJP.MediatrEndpoints as a Cake Addin
#addin nuget:?package=AJP.MediatrEndpoints&version=1.4.1

// Install AJP.MediatrEndpoints as a Cake Tool
#tool nuget:?package=AJP.MediatrEndpoints&version=1.4.1                

api-with-mediatR-without-controllers

Azure DevOps builds Nuget Nuget

Background

There are some increasingly widely help opinions that controllers are somewhat old fashioned. A principal dev where I work demonstrated some middleware which bound MediatR request handlers to routes in an aspnetcore app. As of aspnetcore 3 we now have Endpoint Routing, which easily allows a RequestDelegate to be bound to a route without even needing custom middleware. I wondered if Endpoint Routing + some reflection + MediatR could provide a more modern alternative to controllers and in a real-world use case, would anything be missing?

What is it

A small library which allows Endpoints to be easily registered and wired up to MediatR IRequestHandlers.

The RequestHandlers need/should not have an knowledge of being behind aspnetcore, but instead focus on their business purpose.

When a request is received, public properties from the TRequest type are looked up and satisfied from first the request body, then the route/path variables, then variables from the query string and finally from the request headers collection, if a property is still not found AND not decorated with the Optional attribute, then the request will be returned with a 400BadRequest status code.

The TResponse returned from the RequestHandler is serialised into the response body.

If the TResponse has a public int property named ResponseCode, then it will be used as the response HttpStatusCode, otherwise success is assumed and a 200Ok status code will returned.

If a BadRequestException is thrown, then a 400BadRequest status code will be returned.

If a NotFoundException is thrown, then a 404NotFound status code will be returned. The exception's ResponseBody property will be written to the response body.

If a CustomHttpResponseException is thrown, then the status code contained in the exception will be returned. The exception's TriggerErrorProcessor property determines if the ErrorProcessor will be called and the exception's ResponseBody property will be written to the response body.

If any other Exception is thrown, then a 500InternalServerError status code will be returned.

How to use it

Check out the sample project, basically:

  • Add MediatR package
  • Define some requests, responses and some request handlers as per documentation mediatR wiki
  • Use the services.AddMediatR(typeof(Startup)); extension method to register the types above
  • Add MediatrEndpoints package
  • Define Endpoints using the extension methods
endpoints.MapGroupOfEndpointsForAPath("/api/v1/accounts", "Accounts", "everything to do with accounts")
    .WithGet<GetAccountsRequest, IEnumerable<AccountDetails>>("/")
    .WithGet<GetAccountByIdRequest, AccountDetails>("/{Id}") // route parameter name must match property on TRequest, including case!! otherwise swagger breaks
    .WithPost<CreateAccountRequest, AccountDetails>("/")

Cross cutting concerns (such as request logging stats collection)

The library contains an interface named IMediatrEndpointsProcessors:

public interface IMediatrEndpointsProcessors
{
    Action<HttpContext, ILogger> PreProcess {get; set;}
    Action<HttpContext, TimeSpan, ILogger> PostProcess {get; set;}
    Action<Exception, HttpContext, ILogger> ErrorProcess {get; set;}
}

If an implementation if found in the DI container, its actions will be called at the appropriate times, giving opportunity for request pre and post processing to take place with access to the HttpContext, this makes things like standard logging of requests/responses or timing to take place. E.g. in the sample I check for the presence of a CorrelationId header, create one if it doesn't exist and propergate it to the response headers.

Swagger Support

  • Optionally add Swashbuckle package and configure as per the microsoft docs
  • Then add the AddEndpointsDocumentFilter when configuring SwaggerGen, see the Startup.cs in the sample. c.DocumentFilter<AddEndpointsDocumentFilter>();
  • This will loop through the endpoints registered, pull out some metadata and add paths, operations and parameters accordingly.
  • There are two ways to provide descriptions/example values/parameter location hints:
    1. via the optional parameters when setting up the Endpoints by providing a Dictionary<string, OpenApiParameter> additionalParameterDefinitions when calling WithGet<TRequest, TResponse>() etc
    2. or by decorating the Request and it's properties with a set of supplied Attributes SwaggerQueryParameterAttribute etc

Examples of both methods can be found in the sample project

Testing

The MediatR RequestHandlers can be easily tested by mocking dependencies, passing in a TRequest and Asserting on the returned TResponse.

Component level testing can be achieved using the aspnetcore TestHost to run the service in memory, ideally mocking out any external dependencies.

Licence

MIT, use in any way you like, feel free to contribute 😃

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on AJP.MediatrEndpoints:

Package Downloads
AJP.MediatrEndpoints.Swagger

Small library which adds Swagger OpenApi auto-documentation to AJP.MediatrEndpoints.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.4.1 434 11/2/2022
1.4.0 572 10/22/2022
1.3.0 566 10/24/2021
1.2.0 480 4/3/2021
1.0.1 526 3/14/2021
1.0.0 578 3/13/2021

1.4.1) fixed bug handling integers from the query string and route
   1.4.0) upgrade to net6.0 and latest packages
1.3.0) added ability to configure the endpoint using an optional Action of IEndpointConventionBuilder, for instance to require authorization for an endpoint
1.2.0) swagger support moved to separate package
1.0.1) some internal refactoring
1.0.0) initial version