Regira-Packages

Web Endpoints

Expose entity CRUD operations as HTTP endpoints, through controllers or as mapped minimal-API endpoints. Both serve the same routes and send the same requests:

Package Description
Regira.Entities.Web MVC controllers via EntityControllerBase, or mapped endpoints via MapEntityEndpoints() (Mapped Endpoints)
Regira.Entities.Mediator The requests both surfaces send through IEntitySender (Entity Operations)

Controllers

Controllers provide a more traditional, attribute-based approach using EntityControllerBase. Use this when you need full customisation, a per-entity pipeline with DTO mapping, or advanced sorting and includes.

Controller Selection

// basic (not recommended)
EntityControllerBase<TEntity>
EntityControllerBase<TEntity, TKey>
// basic (using DTOs, recommended)
EntityControllerBase<TEntity, TDto, TInputDto>
EntityControllerBase<TEntity, TSearchObject, TDto, TInputDto>
EntityControllerBase<TEntity, TKey, TSearchObject, TDto, TInputDto>
// complex (advanced operations)
EntityControllerBase<TEntity, TSearchObject, TSortBy, TIncludes, TDto, TInputDto>
EntityControllerBase<TEntity, TKey, TSearchObject, TSortBy, TIncludes, TDto, TInputDto>

Route prefix

Best practice: Keep controller [Route] attributes resource-relative, and spell the resource as the kebab-case plural the mapped endpoints use ([Route("products")], [Route("intervention-types")]). Avoid the [controller] token: it expands to the class-name stem, so an InterventionTypesController serves /InterventionTypes, which a client calling intervention-types does not reach. Apply a shared api base once, in a single configurable place:

Standard Endpoints

Simple and complex controller bases expose different endpoint sets. Simple bases (no TSortBy/TIncludes) expose Details, List (GET), GET /search, Save/Create/Modify/Patch/Delete. Complex bases additionally expose POST /list and POST /search.

Fetch Endpoints

Details (all bases):

// GET /{entities}/{id} - Single entity
Details(id) -> DetailsResult

List (all bases):

// GET /{entities} - Basic List
List() -> ListResult

// GET /{entities}?q={search}&page=1&pageSize=10 - List
List(searchObject, pagingInfo) -> ListResult

// Complex bases only — typed ?includes= and ?sortBy= bind on complex bases; simple bases ignore them
// GET /{entities}?categoryId=1&includes=Category&sortBy=CreatedDesc&sortBy=Title
List(searchObject, pagingInfo, includes[], sortBy[]) -> ListResult

Search (all bases):

// GET /{entities}/search?q={keyword}&page=1 - List + Count combined
// SearchResult carries a total Count alongside the items — use it to drive paging.
Search(searchObject, pagingInfo) -> SearchResult

Complex POST endpoints — complex bases only:

// POST /{entities}/list (collection of SearchObjects in body)
List([FromBody] searchObject[], pagingInfo, includes[], sortBy[]) -> ListResult

// POST /{entities}/search (collection of SearchObjects in body)
Search([FromBody] searchObject[], pagingInfo, includes[], sortBy[]) -> SearchResult

The SearchObject items return queries that are inclusive (using Union).

Paging

List and Search endpoints accept optional page and pageSize query parameters. UseDefaults() sets a default page size of 10 and a maximum of 100, so a request without pageSize gets the first 10 rows; without either setting, it gets the full set. Configure the default and the maximum per app or per entity:

// Global — applies to every entity controller
services.UseEntities<AppDbContext>(options =>
{
    options.UseDefaults();
    // make sure to put this after UseDefaults()
    options.DefaultPageSize = 50;   // used when the request omits pageSize
    options.MaxPageSize = 200;      // any larger requested pageSize is clamped to this
    // or
    options.SetPageSize(pageSize: 50, maxPageSize: 200);
})
// Per-entity override — fully replaces the global values for that entity
.For<Product>(e => e.SetPageSize(defaultPageSize: 25, maxPageSize: 100))
// Opt out — this entity is never force-paged, even when a global default is set
.For<AuditLog>(e => e.SetPageSize());

Save (Add/Modify/Patch)

// POST /{entities} - Create
Create(inputDto) -> SaveResult

// PUT /{entities}/{id} - Full update
Modify(id, inputDto) -> SaveResult

// PATCH /{entities}/{id} - Partial update (JSON Merge Patch, RFC 7386)
Patch(id) -> SaveResult   // body: the partial JSON document

// POST /{entities}/save - Upsert
Save(inputDto) -> SaveResult

PATCH behaviour:

DELETE Endpoint

// DELETE /{entities}/{id} - Delete
Delete(id) -> DeleteResult

Refused writes: a validator that rejects a write makes every write endpoint, DELETE included, answer 400 with a ValidationProblemDetails holding all the errors. In errors each message of a field is its own entry — "" for an error on the entity as a whole — and errorDetails lists every error in order, with its args (Input Exceptions):

{ "title": "One or more validation errors occurred.", "status": 400,
  "errors": { "Code": ["Code is taken.", "Code must start with ORD-."], "": ["The order is incomplete."] },
  "errorDetails": [
    { "key": "Code", "message": "Code is taken." },
    { "key": "Code", "message": "Code must start with ORD-." },
    { "key": "", "message": "The order is incomplete." } ] }

Notes


Mapped Endpoints

An application that wants no controller classes maps its entities instead: app.MapEntityEndpoints(), from Regira.Entities.Web.Endpoints, serves every entity registered through For<>() with the controllers’ routes, request bodies and response envelopes, and the attachment routes under an owner registered with HasAttachments().

using Microsoft.AspNetCore.Builder;
using Regira.Entities.Web.Endpoints;

app.MapEntityEndpoints(o => o.Prefix = "api").RequireAuthorization();

Entity Operations

Each generated endpoint sends a request through IEntitySender, from Regira.Entities.Mediator (which Regira.Entities.Web brings): DetailsQuery, ListQuery, SearchQuery, SaveCommand, PatchCommand and DeleteCommand, with the controller’s type arguments. Code outside a controller — a background job, an import, a minimal-API endpoint of the application’s own — sends the same requests and gets what the endpoint answers: paging defaults, the archived-inclusive lookup of an update, the re-read after a save, the DTO mapping and the result envelope. UseEntities() registers the sender.

flowchart LR
    ctrl["EntityControllerBase"] --> sender["IEntitySender"]
    mapped["MapEntityEndpoints()"] --> sender
    own["Job · importer ·<br/>endpoint of your own"] --> sender
    sender --> behaviors["Pipeline behaviours"]
    behaviors --> handler["Request handler<br/>default or your own"]
    handler --> service["IEntityService"]
    handler --> mapper["IEntityMapper"]
using Regira.Entities.Mediator.Abstractions;
using Regira.Entities.Mediator.Requests;

public class Product : IEntityWithSerial
{
    public int Id { get; set; }
    public string? Title { get; set; }
}
public class ProductDto { public int Id { get; set; } public string? Title { get; set; } }
public class ProductInputDto { public int Id { get; set; } [Required] public string? Title { get; set; } }

public class ProductImporter(IEntitySender sender)
{
    public async Task<ProductDto?> Import(ProductInputDto input, CancellationToken token)
    {
        // null when the product to update does not exist; a refused write throws EntityInputException
        var saved = await sender.Send(new SaveCommand<Product, int, ProductDto, ProductInputDto>(input), token);
        return saved?.Item;
    }
}

Replacing one operation

Register a closed IEntityRequestHandler<TRequest, TResponse> for the request type. It answers in place of the default handler, for the endpoint and for every other sender, with no controller override. Deriving from the default handler, in Regira.Entities.Mediator.Handlers, keeps what it does:

using Regira.Entities.Mediator.Abstractions;
using Regira.Entities.Mediator.Handlers;
using Regira.Entities.Mediator.Requests;
using Regira.Entities.Web.Models;

public class Product : IEntityWithSerial { public int Id { get; set; } public string? Title { get; set; } }
public class ProductDto { public int Id { get; set; } public string? Title { get; set; } public int Stock { get; set; } }

public interface IWarehouse { Task<int> Stock(int productId, CancellationToken token); }

// GET products/{id}, and a job's DetailsQuery, answer with the stock the warehouse holds now
public class ProductDetailsHandler(IServiceProvider services, IWarehouse warehouse)
    : DetailsHandler<Product, int, ProductDto>(services)
{
    public override async Task<DetailsResult<ProductDto>?> Handle(DetailsQuery<Product, int, ProductDto> request, CancellationToken token = default)
    {
        var result = await base.Handle(request, token);
        if (result != null)
        {
            result.Item.Stock = await warehouse.Stock(result.Item.Id, token);
        }
        return result;
    }
}

public static class ProductOperations
{
    public static IServiceCollection AddProductOperations(this IServiceCollection services)
        => services.AddTransient<IEntityRequestHandler<DetailsQuery<Product, int, ProductDto>, DetailsResult<ProductDto>>, ProductDetailsHandler>();
}

A request of your own

An operation the standard requests do not cover can be a request of the application’s own. It implements IEntityRequest<TResponse> and declares the entity and the operation, which a behaviour reads. It has no default handler, so it needs a registered one, and its first send says so when that is missing:

using Regira.Entities.Mediator;
using Regira.Entities.Mediator.Abstractions;
using Regira.Entities.Mediator.Requests;
using Regira.Entities.Web.Models;

public class Product : IEntityWithSerial { public int Id { get; set; } public string? Title { get; set; } public decimal Price { get; set; } }
public class ProductDto { public int Id { get; set; } public string? Title { get; set; } public decimal Price { get; set; } }
public class ProductInputDto { public int Id { get; set; } [Required] public string? Title { get; set; } public decimal Price { get; set; } }

// a behaviour sees the copy as a Save of Product
public sealed record DuplicateProduct(int Id) : IEntityRequest<SaveResult<ProductDto>>
{
    Type IEntityRequest.EntityType => typeof(Product);
    EntityOperation IEntityRequest.Operation => EntityOperation.Save;
}

public class DuplicateProductHandler(IEntityService<Product, int> service, IEntitySender sender)
    : IEntityRequestHandler<DuplicateProduct, SaveResult<ProductDto>>
{
    public async Task<SaveResult<ProductDto>?> Handle(DuplicateProduct request, CancellationToken token = default)
    {
        var original = await service.Details(request.Id, token);
        if (original == null)
        {
            return null;
        }
        // saved as POST products saves it: the input checked, the write pipeline run, the copy re-read and mapped
        var copy = new ProductInputDto { Title = $"{original.Title} (copy)", Price = original.Price };
        return await sender.Send(new SaveCommand<Product, int, ProductDto, ProductInputDto>(copy), token);
    }
}

public static class ProductCopies
{
    public static IServiceCollection AddProductCopies(this IServiceCollection services)
        => services.AddTransient<IEntityRequestHandler<DuplicateProduct, SaveResult<ProductDto>>, DuplicateProductHandler>();
}

An endpoint or a job sends it like the standard requests: await sender.Send(new DuplicateProduct(id), token). The SaveCommand it sends passes the behaviours too, so an operation log records a Save of Product twice.

Replacing one endpoint

For what belongs to HTTP — an attribute, a header, a status code, a parameter the request does not carry — replace the endpoint rather than the handler.

On a controller, override the generated action. The actions are virtual, and the override inherits the verb and route attributes and the parameters’ binding attributes, so it declares only what it adds:

using Microsoft.AspNetCore.Authorization;
using Regira.DAL.Paging;
using Regira.Entities.Web.Controllers.Abstractions;
using Regira.Entities.Web.Models;

public class Product : IEntityWithSerial { public int Id { get; set; } public string? Title { get; set; } }
public class ProductDto { public int Id { get; set; } public string? Title { get; set; } }
public class ProductInputDto { public int Id { get; set; } [Required] public string? Title { get; set; } }

[ApiController, Route("products")]
public class ProductController : EntityControllerBase<Product, ProductDto, ProductInputDto>
{
    // still GET products?q=…&page=…: the route and the query binding come from the base action
    [Authorize(Policy = "Catalog")]
    public override Task<ActionResult<ListResult<ProductDto>>> List(SearchObject so, PagingInfo pagingInfo)
    {
        Response.Headers.CacheControl = "private, max-age=60";
        return base.List(so, pagingInfo);
    }
}

Keep the signature exactly: a method with another parameter list is no override but a new action, which inherits none of the base action’s attributes: under [ApiController] its complex parameters bind from the body, so a search object beside PagingInfo makes MapControllers() throw at startup. The complex bases’ POST list and POST search are overridden on their own.

On mapped endpoints there is no action to override: exclude the generated endpoint and map your own on the entity’s route group, sending the same request so a handler override and the behaviours still apply:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Regira.DAL.Paging;
using Regira.Entities.DependencyInjection.ServiceCollections;
using Regira.Entities.Mapping.Mapster;
using Regira.Entities.Mediator.Abstractions;
using Regira.Entities.Mediator.Requests;
using Regira.Entities.Web.Endpoints;

public class Product : IEntityWithSerial { public int Id { get; set; } public string? Title { get; set; } }
public class ProductDto { public int Id { get; set; } public string? Title { get; set; } }
public class ProductInputDto { public int Id { get; set; } [Required] public string? Title { get; set; } }

public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
    public DbSet<Product> Products => Set<Product>();
}

public static class ShopConfiguration
{
    public static EntityServiceCollection<AppDbContext> AddShop(this IServiceCollection services)
        => services
            .UseEntities<AppDbContext>(o =>
            {
                o.UseDefaults();
                o.UseMapsterMapping();                                  // the mapper UseMapping configures
            })
            .For<Product>(e =>
            {
                e.UseMapping<ProductDto, ProductInputDto>();
                e.Endpoints(o => o.Exclude(EntityEndpoint.List));          // GET products is the app's own below
            });

    public static IEndpointRouteBuilder MapShop(this IEndpointRouteBuilder app)
    {
        app.MapEntityEndpoints(o => o.ConfigureGroup<Product>(products => products
            .MapGet("", async (IEntitySender sender, HttpContext http, string? q, int? page, int? pageSize) =>
            {
                http.Response.Headers.CacheControl = "private, max-age=60";
                var paging = new PagingInfo { Page = page ?? 1, PageSize = pageSize };
                return Results.Ok(await sender.Send(new ListQuery<Product, int, SearchObject, ProductDto>(new SearchObject { Q = q }, paging)));
            })
            .WithMetadata(new EntityEndpointMetadata(typeof(Product), EntityEndpoint.List))));
        return app;
    }
}

Behaviours

An IEntityPipelineBehavior<TRequest, TResponse> runs around a request’s handler: caching, or a log of the operation itself, reads and refused attempts included. Registered as an open generic it runs around every request, and IEntityRequest.EntityType and IEntityRequest.Operation tell which entity and which operation:

using Microsoft.Extensions.Logging;
using Regira.Entities.Mediator.Abstractions;

public class OperationLog<TRequest, TResponse>(ILogger<OperationLog<TRequest, TResponse>> logger)
    : IEntityPipelineBehavior<TRequest, TResponse>
    where TRequest : IEntityRequest<TResponse>
{
    public async Task<TResponse?> Handle(TRequest request, EntityRequestDelegate<TResponse> next, CancellationToken token = default)
    {
        try
        {
            return await next();
        }
        finally
        {
            logger.LogInformation("{Operation} {Entity}", request.Operation, request.EntityType.Name);
        }
    }
}

public static class OperationLogging
{
    public static IServiceCollection AddOperationLog(this IServiceCollection services)
        => services.AddTransient(typeof(IEntityPipelineBehavior<,>), typeof(OperationLog<,>));
}

Registered closed, a behaviour runs around that one request type alone:

using Microsoft.Extensions.Logging;
using Regira.Entities.Mediator.Abstractions;
using Regira.Entities.Mediator.Requests;
using Regira.Entities.Web.Models;

public class Product : IEntityWithSerial { public int Id { get; set; } public string? Title { get; set; } }
public class ProductDto { public int Id { get; set; } public string? Title { get; set; } }

// every attempt to delete a product — failed and not-found ones included — whatever sent it
public class ProductDeleteLog(ILogger<ProductDeleteLog> logger)
    : IEntityPipelineBehavior<DeleteCommand<Product, int, ProductDto>, DeleteResult<ProductDto>>
{
    public async Task<DeleteResult<ProductDto>?> Handle(DeleteCommand<Product, int, ProductDto> request,
        EntityRequestDelegate<DeleteResult<ProductDto>> next, CancellationToken token = default)
    {
        var outcome = "failed";
        try
        {
            var result = await next();
            outcome = result == null ? "not found" : "deleted";
            return result;
        }
        finally
        {
            logger.LogInformation("Delete of product {Id}: {Outcome}", request.Id, outcome);
        }
    }
}

public static class ProductDeleteLogging
{
    public static IServiceCollection AddProductDeleteLog(this IServiceCollection services)
        => services.AddTransient<IEntityPipelineBehavior<DeleteCommand<Product, int, ProductDto>, DeleteResult<ProductDto>>, ProductDeleteLog>();
}

A mediator library

To run every entity request inside the application’s own mediator pipeline — logging, tracing, authorization, a unit of work around the generated endpoints as around its other requests — replace the IEntitySender registration with a sender that sends one message type through the library. With MediatR:

using MediatR;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Regira.Entities.Mediator;
using Regira.Entities.Mediator.Abstractions;

// one message for every entity request; Run sends it on to the in-house sender, typed
public sealed record EntityMessage(IEntityRequest Request, Func<IEntitySender, CancellationToken, Task<object?>> Run) : IRequest<object?>;

public class EntityMessageHandler(IServiceProvider services) : IRequestHandler<EntityMessage, object?>
{
    public Task<object?> Handle(EntityMessage message, CancellationToken token)
        => message.Run(ActivatorUtilities.CreateInstance<EntitySender>(services), token);
}

public class MediatREntitySender(ISender mediator) : IEntitySender
{
    public async Task<TResponse?> Send<TResponse>(IEntityRequest<TResponse> request, CancellationToken token = default)
        => (TResponse?)await mediator.Send(new EntityMessage(request, async (inner, t) => await inner.Send(request, t)), token);
}

// one of the application's behaviours: it reads the entity request on the message to tell a read from a write
public class WriteLog<TRequest, TResponse>(ILogger<WriteLog<TRequest, TResponse>> logger) : IPipelineBehavior<TRequest, TResponse>
    where TRequest : notnull
{
    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
    {
        if (request is EntityMessage { Request.Operation: EntityOperation.Save or EntityOperation.Patch or EntityOperation.Delete } message)
        {
            logger.LogInformation("{Operation} {Entity}", message.Request.Operation, message.Request.EntityType.Name);
        }
        return await next();
    }
}

// in the application's registration, before or after UseEntities()
public static class EntityMediatR
{
    public static IServiceCollection AddEntityMediatR(this IServiceCollection services)
    {
        services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<EntityMessage>());
        services.AddTransient(typeof(IPipelineBehavior<,>), typeof(WriteLog<,>));
        services.Replace(ServiceDescriptor.Scoped<IEntitySender, MediatREntitySender>());
        return services;
    }
}

Response Types

Both approaches return the same standardised result wrappers:

public record DetailsResult<TDto>
{
    public TDto Item { get; set; }
    public long? Duration { get; set; } // Execution time in ms
}

public record ListResult<TDto>
{
    public IList<TDto> Items { get; set; }
    public long? Duration { get; set; }
}

public record SearchResult<TDto>
{
    public IList<TDto> Items { get; set; }
    public long Count { get; set; } // Total count for pagination
    public long? Duration { get; set; }
}

public record SaveResult<TDto>
{
    public long? Duration { get; set; }
    public bool IsNew { get; set; }
    public int Affected { get; set; }
    public TDto Item { get; set; }
}

public record DeleteResult<TDto>
{
    public TDto Item { get; set; } // The deleted item
    public int Affected { get; set; } // Rows written; a soft delete writes one too
    public long? Duration { get; set; }
}

The result types ship in Regira.Entities.Mediator, under the Regira.Entities.Web.Models namespace.


Overview

  1. Index — Overview of Regira Entities
  2. Entity Models — Creating and structuring entity models
  3. Services — Implementing entity services, repositories and the write pipeline
  4. Mapping — Mapping Entities to and from DTOs
  5. Web Endpoints — Exposing entity operations as HTTP endpoints
  6. Normalizing — Data normalization techniques
  7. Attachments — Managing file attachments
  8. Built-in Features — Ready to use components
  9. Checklist — Step-by-step guide for common tasks
  10. Practical Examples — Complete implementation examples