MediatR.Endpoints 1.1.0

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

MediatR.Endpoints

NuGet

Combines ASP.NET Core Minimal APIs with MediatR for simple, painless mapping of requests to REST API endpoints.

Installing MediatR.Endpoints

You should install MediatR with NuGet:

Install-Package MediatR.Endpoints

Or via the .NET Core command line interface:

dotnet add package MediatR.Endpoints

All required dependencies will be installed, including MediatR.

Quick Start

Call AddMediatREndpoints during service configuration, after calling AddMediatR. Assemblies registered in AddMediatR will be scanned for endpoints.

builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
builder.Services.AddMediatREndpoints();

Then call MapMediatREndpoints to find and build your endpoints:

var app = builder.Build();
app.MapMediatREndpoints();

That's it. Any endpoints configured using one or more of the methods below will be automatically created to spec.

Endpoint Configuration

An endpoint consists of the following properties:

  • <b>RequestType:</b> <i>Required.</i> The IRequest or IRequest<TResponse> object to which the endpoint is mapped.
  • <b>HttpMethod:</b> <i>Required.</i> Get, Post, Patch, Put, and Delete are supported.
  • <b>Route:</b> <i>Optional.</i> If omitted, the endpoint route will be generated by applying the DefaultRouteFormatter to the IRequestType learn more
  • <b>Group:</b> <i>Optional.</i> If omitted, group defaults to an empty string. Group is prefixed to the route and can be used to organize endpoints and/or apply unique functionality to a group of related endpoints.
  • <b>RouteHandlerBuilder:</b> <i>Optional.</i> A delegate to build conventions to customize the endpoint action.
  • <b>Handler:</b> <i>Optional.</i> Overrides the default action handler. learn more

Mapping

There are three ways to map an endpoint:

  1. Using the Endpoint attribute
  2. Using an IEndpointConfiguration<TRequest> class
  3. Using MediatREndpointsConfiguration during service configuration
Using the Endpoint attribute

Apply directly to an IRequest or IRequest<TResponse> object

[Endpoint(Method.Get, "my/route/{id}", Group = "mygroup")]
public class MyGetRequest : IRequest<string>
{
    public int Id { get; set; }
}

or to a class the request object is nested under.

[Endpoint(Method.Get, "my/route/{id}", Group = "mygroup")]
public class MyGetRequest
{
    public class Query : IRequest<string>
    {
        public int Id { get; set; }
    }
}

Route and Group are optional.

[Endpoint(Method.Get)] 
...
[Endpoint(Method.Get, "my/route"]
...
[Endpoint(Method.Get, "my/route", Group = "mygroup"]
...
Using an IEndpointConfiguration<TRequest> class

Create an IEndpointConfiguration class and implement the Configure method. This class can exist anywhere in your registered assemblies; it can even be the request itself. All IEndpointDefinition properties are optional.

public class MyGetRequestConfiguration : IEndpointConfiguration<MyGetRequest>
{
    public void Configure(IEndpointDefinition e)
    {
        e.HttpMethod = Method.Get;
        e.Route = "my/route/{id}";
        e.Group = "mygroup";
}
Using MediatREndpointsConfiguration:

Use the methods on MediatREndpointsConfiguration during service configuration. Methods exist for GET, POST, PATCH, PUT, and DELETE endpoints. All parameters are optional.

builder.Services.AddMediatREndpoints(cfg => 
{         
    cfg.MapGet<MyGetRequest>("my/route/{id}", "mygroup");
    cfg.MapPost<MyPostRequest>();
}

Custom route handle builders

Endpoint conventions can be customized per endpoint, per group of endpoints, or globally.

To customize a single endpoint, set the RouteHandlerBuilder:

In service configuration:

cfg.MapGet<MyGetRequest>(a => a
    .RequireAuthorization()
    .AddEndpointFilter<EndpointFilter>());

Or in an IEndpointConfiguration<TRequest> class:

public class MyGetRequestConfiguration : IEndpointConfiguration<MyGetRequest>
{
    public void Configure(IEndpointDefinition e)
    {
        e.HttpMethod = Method.Get;
        e.RouteHandlerBuilder = a => a
            .RequireAuthorization()
            .AddEndpointFilter<MyEndpointFilter>();
    }
}

To customize multiple endpoints, use AddGroupRouteBuilder during service configuration:

// Applies to endpoints in group "myGroup"
cfg.AddRouteGroupBuilder("myGroup", a => a
    .RequireAuthorization()
    .AddEndpointFilter<EndpointFilter>());

// Omit the Group parameter to applies to ALL endpoints
cfg.AddRouteGroupBuilder(a => a
    .RequireAuthorization()
    .AddEndpointFilter<EndpointFilter>());

Custom endpoint action handler

The default actions for endpoints are kept thin and simple, like this:

async (IMediator mediator, [FromBody] TRequest request) =>
{
    return await mediator.Send(request);
};

There are minor variations depending on request method and type. See DefaultEndpointHandlerDelegateFactory for all actions.

Additional functionality like validation, logging, and error handling is typically applied through route builders, but if necessary the action handlers can be customized per endpoint or globally.

To customize a single endpoint, set the Handler:

In service configuration:

cfg.MapPut<MyPutRequest>("my/put/{id}", handler:
    async (SomeDependency dependency, IMediator mediator, int id, [FromBody]string name) =>
    {
        var request = new MyGetRequest
        {
            Id = id,
            Name = dependency.DoSomething(name),                  
            Date = DateTime.Now.AddDays(3).Date
        };
        var response = await mediator.Send(request);
        return Results.Ok(response);
    });

Or in an IEndpointConfiguration<TRequest> class:

public class MyPutRequestConfiguration : IEndpointConfiguration<MyPutRequest>
{
    public void Configure(IEndpointDefinition e)
    {
        e.HttpMethod = Method.Put;
        e.Route = "my/put/{id},"
        e.Handler = async (SomeDependency dependency, IMediator mediator, int id, [FromBody]string name) =>
        {
            var request = new MyGetRequest
            {
                Id = id,
                Name = dependency.DoSomething(name),                  
                Date = DateTime.Now.AddDays(3).Date
            };
            var response = await mediator.Send(request);
            return Results.Ok(response);
        });
    }
}

To customize the handler(s) for all endpoints, create your own factory:

public class MyHandlerFactory : DefaultEndpointHandlerDelegateFactory
{
    public override Delegate GetHandler<TRequest, TResponse>()
    {
        // return custom delegate action
    }
}

Then register during service configuration:

cfg.UseEndpointHandlerDelegateFactory<MyHandlerFactory>();

Default Route Formatter

When an endpoint route is not explicitly defined, it will be automatically generated using the DefaultRouteFormatter. The default function removes all non-alphanumeric characters from the full type name, then replaces . with /. For example:

Type: Api.Features.Stuff.MyRequest
Route: Api/Features/Stuff/MyRequest

This formatter can be overridden during service configuration:

cfg.DefaultRouteFormatter = (t) => $"custom/default/route/{t.Name}"
// Result:
//  Type: Api.Features.Stuff.MyRequest
//  Route: custom/default/route/MyRequest
Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  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.  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.1.0 385 10/31/2023
1.0.3 179 10/30/2023
1.0.2 187 10/29/2023
1.0.1 183 10/28/2023
1.0.0 175 10/28/2023