Skip to content

ASP.NET Core (Handler to Endpoint)

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;

  1. Install Shiny.Mediator.AspNet to your ASP.NET Core project.

  2. On your request handler (void or result based), add [MediatorHttpPost("MyRoute")] or [MediatorHttpPut("MyRoute")] attribute to the handler.

    public class MyHandler : IRequestHandler<MyRequest, MyResult>
    public async Task<MyResult> Handle(MyRequest request, CancellationToken ct)
    return new MyResult();
  3. In your host startup, register your handler (or use the source generator attributes).

  4. Again, in your host startup, add the following after your build your app. Here is a full-ish sample

    var builder = WebApplication.CreateBuilder(args);
    var app = builder.Build();

Here is a list of all the properties supported by the Http attributes

public class MediatorHttpAttribute(string uriTemplate, HttpMethod httpMethod) : Attribute
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