ASP.NET Core (Handler to Endpoint)
Setup
Shiny Mediator now can map up your request handlers to ASP.NET Core endpoints using the minimal API. This saves you the effort of implementing the following boilerplate over and over and over again
app.MapPost("/api/MyResultHandler", async (IMediator mediator, MyRequest request, CancellationToken ct) =>{ return await mediator.Request(request, ct);});
The only thing that changes in this setup is the http method type, request type, and route. Now, all you have to do is following;
-
On your request handler (void or result based), add
[MediatorHttpPost("OperationId", "MyRoute")]
or[MediatorHttpPut("OperationId", "MyRoute")]
(GET & DELETE attributes also available) attribute to the handler.[MediatorHttpPost("TheOperationId", "MyRoute")]public class MyHandler : IRequestHandler<MyRequest, MyResult>{public async Task<MyResult> Handle(MyRequest request, RequestContext<MyRequest> context, CancellationToken ct){return new MyResult();}} -
In your host startup, add the following after your build your app. Here is a full-ish sample
var builder = WebApplication.CreateBuilder(args);// MAKE MEDIATOR AVAILABLEbuilder.Services.AddShinyMediator();// ADD YOUR HANDLER(S)services.AddScopeAsImplementedInterfaces<MyHandler>();var app = builder.Build();// ADD REGISTERED HANDLERS THAT ARE ATTRIBUTED TO THE HTTP ENDPOINTSapp.MapShinyMediatorEndpointHandlers(builder.Services);app.Run();
Here is a list of all the properties supported by the Http attributes
public class MediatorHttpAttribute(string operationId, string uriTemplate, HttpMethod httpMethod) : Attribute{ public string OperationId => operationId; public string UriTemplate => uriTemplate; public HttpMethod Method => httpMethod;
public bool RequiresAuthorization { get; set; } public string[]? AuthorizationPolicies { get; set; } public string? DisplayName { get; set; } public string? GroupName { get; set; } public string[]? Tags { get; set; } public string? Description { get; set; } public string? Summary { get; set; } public bool UseOpenApi { get; set; } = true; public string? CachePolicy { get; set; } public string? CorsPolicy { get; set; } public bool ExcludeFromDescription { get; set; } public string? RateLimitingPolicy { get; set; } public bool AllowAnonymous { get; set; }}
It is best to register most handlers and middleware as Scoped
on ASP.NET Core apps
MediatorHttpGet & MediatorHttpDelete parameters can only be set on the route or querystring
Minimal API Registration
Minimal API allows you some fine grained control that attribute registration may restrict as it returns the standard RouteHandleBuilder
object that
ASP.NET registration returns
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddShinyMediator();builder.Services.AddDiscoveredMediatorHandlersFromYOUR_APP();
var app = builder.Build();
// fluent registration can be mixed with the attribute registrationapp.MapMediatorGet<MappedRequest, string>("/mapped").WithOpenApi();
app.Run();