Hmz.Core.SharedKernel
0.1.20
See the version list below for details.
dotnet add package Hmz.Core.SharedKernel --version 0.1.20
NuGet\Install-Package Hmz.Core.SharedKernel -Version 0.1.20
<PackageReference Include="Hmz.Core.SharedKernel" Version="0.1.20" />
<PackageVersion Include="Hmz.Core.SharedKernel" Version="0.1.20" />
<PackageReference Include="Hmz.Core.SharedKernel" />
paket add Hmz.Core.SharedKernel --version 0.1.20
#r "nuget: Hmz.Core.SharedKernel, 0.1.20"
#:package Hmz.Core.SharedKernel@0.1.20
#addin nuget:?package=Hmz.Core.SharedKernel&version=0.1.20
#tool nuget:?package=Hmz.Core.SharedKernel&version=0.1.20
Hmz.Core.SharedKernel
Hmz.Core.SharedKernel 0.1.20 targets .NET 10 and provides reusable application, domain-support, EF Core, advanced-search, authorization, and ASP.NET Core boundary contracts.
Results and errors
Use Result and Result<T> for expected application failures:
using Hmz.Core.SharedKernel.Results;
public Result<Order> CreateOrder(string customerId)
{
if (string.IsNullOrWhiteSpace(customerId))
{
return Result.Failure<Order>(Error.Validation(
"order.customer-required",
"Customer is required.",
"customerId"));
}
return Result.Success(new Order(customerId));
}
Errors carry a stable code, safe message, transport-neutral category, and optional validation target. Failed results may contain multiple errors of one category. Use Match, Map, and Bind for composition. Unexpected failures remain exceptions and are handled at the application boundary.
Generate diagnostic codes with ErrorCode.Create:
public static readonly string ProductItemsNotFound = ErrorCode.Create(
"CM",
ErrorType.NotFound,
"product-items");
// CM.NOTF.PRODUCT-ITEMS
Use a short, stable application/module prefix. Do not repeat the error type in the semantic suffix.
Use Error.BusinessRule(code, message, target?) (code segment RULE) when a well-formed request breaks a business rule: a transition the current state refuses, a total over a limit, a document that needs at least one line. ToProblem answers 422 "Business rule violated"; document it with .ProducesBusinessRuleProblem(). Keep Validation (400) for the shape of the request: a field that is missing, too long or malformed. Moving a code from .VAL. to .RULE. is a contract change for clients that match codes. Problem Details carry the error's target as a target extension when it has one.
Result<T> requires T : notnull. Return a lookup type, an empty collection or a not-found failure instead of Result<Item?>; a generic helper or pipeline behavior that wraps Result<T> adds where T : notnull too.
Pagination
using Hmz.Core.SharedKernel.Contracts.Pagination;
return new PagedResponse<OrderResponse>(items, page, pageSize, totalCount);
Messaging and identity
Hmz.Core.SharedKernel.Messaging provides ICommand, IQuery, INotification, and corresponding handler contracts over Mediator abstractions.
Hmz.Core.SharedKernel.Identity.Abstractions.ICurrentUser is the shared current-user boundary. Applications own authentication, claims mapping, profile lookup, and authorization policy.
Integration events and messages
The Messaging sub-namespaces add cross-module communication for modular
monoliths. They distinguish two kinds of communication:
| Integration event | Message | |
|---|---|---|
| Meaning | A fact that already happened in one module | A notification that only matters now |
| Durability | Written to the producer's outbox in the same transaction as the state change; kept and replayable | Not persisted; lost if the process stops |
| Delivery | At least once, with retry, backoff, and dead-lettering; consumers are idempotent through an inbox | At most once, no retry |
| Use for | Keeping modules consistent | Cache invalidation, live notifications, telemetry |
| Namespace | Messaging.IntegrationEvents, .Outbox, .Inbox, .Transport |
Messaging.Messages |
Domain events (EventDispatcherInterceptor) remain in-process, after-commit
side effects inside one module and are not a substitute for either.
Defining and publishing an integration event
[IntegrationEventName("media.attachments-changed.v1")] // stable wire name; version it, never rename it
public sealed record MediaAttachmentsChanged(...) : IntegrationEvent;
// UseCase: each module exposes its own outbox interface, like its unit of work.
public interface ICatalogOutbox : IIntegrationEventOutbox;
outbox.Add(new MediaAttachmentsChanged(...)); // tracked only
await unitOfWork.SaveChangesAsync(ct); // commits the row change and the outbox row together
Infrastructure wires the outbox into the module DbContext:
// OnModelCreating
modelBuilder.AddOutboxMessages(); // producer: <schema>.OutboxMessages
modelBuilder.AddInboxMessages(); // consumer: <schema>.InboxMessages
// DbContext options
options.AddOutboxNotifications(serviceProvider); // wakes the processor right after commit
// Services
services.AddIntegrationEventOutbox<AppDbContext>(configuration);
services.AddScoped<ICatalogOutbox, CatalogOutbox>(); // : EfIntegrationEventOutbox<AppDbContext>
services.AddIntegrationEventHandler<MediaAttachmentsChanged, Handler, MediaDbContext>(configuration);
Delivery flow
- A request handler changes state and calls
outbox.Add(event); oneSaveChangesAsynccommits both rows. OutboxNotificationInterceptorsignals the module'sOutboxProcessor<TDbContext>after the commit (it also polls everyMessaging:Outbox:PollInterval).- The processor leases a batch in one short statement
(
UPDATE … SET "LockedUntil" … WHERE "Id" IN (SELECT … FOR UPDATE SKIP LOCKED) RETURNING *) and commits. No transaction stays open during delivery, any number of hosts can run processors, and rows of a crashed host become claimable when their lease expires. - Events are delivered outside any transaction, up to
Messaging:Outbox:DeliveryConcurrencyat a time, through the transport selected byMessaging:Transport. The built-inInMemoryIntegrationEventTransportis a bounded channel that completes only when every subscriber acknowledges; broker transports complete on the broker's publisher confirm. Each outcome is written back individually and releases the lease; a late failure never overwrites another host's success. IntegrationEventDispatcherruns each subscription in its own DI scope. The inbox wrapper opens a transaction on the consumer's DbContext, skips events already in its inbox, runs the handler, and records the inbox row in the same transaction.- On success the outbox row is marked processed. On failure it is retried
with exponential backoff up to
Messaging:Outbox:MaxAttempts, then dead-lettered. Processed rows are kept forProcessedRetentionandOutboxReplayer<TDbContext>can requeue them; consumers that already handled a replayed event skip it.
Handlers run in background scopes without an HTTP user, so they must not
depend on ICurrentUser; carry the actor in the event if it matters.
Events published while a handler runs inherit its correlation id and record
the handled event as their CausationId (IntegrationEventScope); outside a
handler the correlation id is the current trace id.
Module-private events
A module can publish an event that only it consumes: write it through its own
EfIntegrationEventOutbox<ModuleDbContext> and subscribe with
AddIntegrationEventHandler<E, H, ModuleDbContext>. Retry, backoff,
dead-lettering and inbox deduplication work as for cross-module events.
- Register one handler per private event. The dispatcher fails the whole envelope when any subscriber fails, so a second handler would be retried with it.
- Nothing marks an event as local yet.
OutboxProcessorsends every row to the singleIIntegrationEventTransport, so a broker transport would publish private events too. The first external transport needs a local-only marker that keeps them in process. - A handler runs inside the inbox transaction on the module's DbContext, which
InboxSubscriptionopens before it calls the handler. That one transaction saves the handler's changes and the inbox row, so any call the handler makes to another system holds the transaction open. Keep it to one short call, or move bulk external work to a job that reads outside any transaction.
Transports and scaling out
// A broker package registers its transport and its own consumer host:
services.AddIntegrationEventTransport<RabbitMqIntegrationEventTransport>("RabbitMq");
// The consumer host delivers each queue to one consumer, so queues retry independently:
await dispatcher.DispatchToConsumerAsync(envelope, consumerName, cancellationToken);
Switch environments with Messaging:Transport (InMemory by default); an
unregistered name fails at startup resolution with a clear error. Broker
consumer hosts can enumerate IntegrationEventRegistry.All to declare one
queue per consumer.
Observability
Register MessagingTelemetry.Name (Hmz.Core.Messaging) with OpenTelemetry
AddSource and AddMeter. Activities: deliver {event} (producer) and
handle {event} (consumer) tagged with message id, correlation id, causation
id, consumer, and attempt. Metrics: hmz.messaging.outbox.delivered,
.failed, .dead_lettered, hmz.messaging.outbox.delivery.duration (ms),
hmz.messaging.inbox.handled, and hmz.messaging.inbox.duplicates.
Fire-and-forget messages
services.AddMessageHandler<ProductCacheInvalidated, InvalidateProductCache>();
messageBus.Publish(new ProductCacheInvalidated(productId)); // returns false when dropped
Configuration
| Key | Default | Purpose |
|---|---|---|
Messaging:Enabled |
true |
Runs processors, transports, and housekeeping; disable for tooling-only hosts. |
Messaging:Transport |
InMemory |
Registered transport name to use. |
Messaging:Outbox:LeaseDuration |
00:02:00 |
Claim lease; keep above the slowest delivery. |
Messaging:Outbox:DeliveryConcurrency |
1 |
Deliveries in flight per processor; 1 keeps per-instance order. |
Messaging:Inbox:Retention |
45.00:00:00 |
Inbox purge age; must be at least ProcessedRetention. |
Messaging:Outbox:PollInterval |
00:00:05 |
Fallback poll when no commit signal arrives. |
Messaging:Outbox:BatchSize |
50 |
Rows claimed per batch. |
Messaging:Outbox:MaxAttempts |
10 |
Attempts before dead-lettering. |
Messaging:Outbox:MaxBackoff |
00:05:00 |
Backoff cap. |
Messaging:Outbox:ProcessedRetention |
30.00:00:00 |
Replay window before processed rows are purged. |
Messaging:TransportCapacity / TransportConcurrency |
256 / 4 |
In-memory transport queue and consumers. |
Messaging:MessageBusCapacity |
10000 |
Fire-and-forget queue length before messages are dropped. |
The outbox claim query uses PostgreSQL SKIP LOCKED syntax. Applications own
the outbox and inbox migrations in each module schema.
Known limitations (deferred)
Recorded during the 0.1.15 review and intentionally not implemented
yet; none can deadlock, and the first only matters with several instances.
- Lease per batch. A batch shares one lease taken at claim time. With
several instances and sequential delivery, rows late in a large batch can
outlive
LeaseDurationand be redelivered by another instance (the inbox absorbs it). Planned: renew the lease per message before delivery. - Claim sort under backlog. The pending index leads with
NextAttemptAtwhile the claim orders byOccurredAt, so a large backlog is sorted on each poll. Planned: a pending partial index on(OccurredAt, Id). - Unbatched retention deletes. Outbox and inbox purges run one delete per sweep. Planned: bounded batch deletes.
Secret comparison
Use FixedTimeSecretComparer.Equals(expected, actual) for application-owned
API keys, webhook signatures, and similar shared-secret checks. The helper
hashes both values to fixed-size buffers before using
CryptographicOperations.FixedTimeEquals, so differing input lengths do not
reintroduce an early-exit comparison.
Keep secret resolution and rotation in the consuming application. This helper does not read configuration, log values, define an authentication scheme, or replace a real identity provider when user identity and authorization are required.
Security also provides RandomCode.Create(alphabet, length) (cryptographically
random codes drawn uniformly from an alphabet) and Sha256Hex.Hash(value)
(lower-case hex SHA-256 of the UTF-8 bytes, Sha256Hex.Length characters), for
example to issue a one-time code and store only its hash. Sha256Hex.Hash(bytes)
hashes raw bytes. Sha256Hex.HashJson(value, serializerOptions) hashes the UTF-8
JSON of a value, for a fingerprint of stored content or an opaque ETag. Pass the
same options every time, and normalize decimals first with
Serialization.DecimalNormalizationExtensions.WithoutTrailingZeros():
150.0000m from a numeric(18,4) column and 150m are equal but serialize
differently.
Secret protection
ISecretProtector encrypts a third-party secret (a CMS API key, a token per
tenant) for storage with AES-256-GCM. Register it with a key ring from
configuration:
builder.Services.AddSecretProtector(builder.Configuration.GetSection("SecretProtector"));
{
"SecretProtector": {
"ActiveKeyId": "2026-11",
"Keys": { "2026-11": "<base64 of 32 random bytes>" }
}
}
Generate a key (put it in the environment's secret store, never in the repository or the database):
[Convert]::ToBase64String([Security.Cryptography.RandomNumberGenerator]::GetBytes(32))
openssl rand -base64 32
Environment variables: SecretProtector__ActiveKeyId, SecretProtector__Keys__2026-11.
var secret = protector.Protect(Encoding.UTF8.GetBytes($"channel.{channel.Id}"), apiKey);
// store secret.Ciphertext and secret.KeyId
var plain = protector.Unprotect(Encoding.UTF8.GetBytes($"channel.{channel.Id}"), stored);
var hint = SecretHint.Last(apiKey); // "(ellipsis)6789"; null for a short secret, never for a password
- The associated data is required and is not stored. Use a stable identity of the owner (the row id, with a type prefix), so a ciphertext copied to another row does not decrypt.
- A secret that cannot be decrypted (key removed, other associated data, a
changed value) throws
SecretProtectionException, as it is not an expected business outcome.TryUnprotectreturnsfalsefor a caller that asks the user to enter the secret again. - With no key configured the app starts and
IsConfiguredisfalse;ProtectandUnprotectthrowInvalidOperationException. CheckIsConfiguredand answer 503. A malformed key (bad base64, not 32 bytes) or anActiveKeyIdwithout a key fails the start. - The stored value is base64 of nonce (12 bytes), tag (16 bytes) and
ciphertext, so existing Monosbase Publishing rows decrypt unchanged when the
associated data bytes are the ones it used (
publishing.channel.{id}).
Rotation:
- Add a new key under a new id, and keep the old one.
- Set
ActiveKeyIdto the new id and deploy. New secrets use it; old ones still decrypt with the key id stored beside them. - Re-protect: for each row with
NeedsReprotect(row.KeyId),Unprotectwith the stored value andProtectagain, then save both columns. - When no row names the old key id, remove the key.
Why not ASP.NET Core Data Protection: its key ring is kept on the local file system by default, and when it is not persisted (containers redeployed without a shared volume) every deploy creates new keys and earlier ciphertexts can no longer be read. Here the keys are explicit configuration, so they survive redeploys and rotate on purpose.
Internal API keys
Http.Authentication authenticates internal callers (another service, a
worker, a scheduled job) with an API key, for internal APIs where a full
OAuth2 client-credentials flow is not worth it or no identity provider runs.
Members keep signing in through the identity provider.
A key reads <prefix>_<keyId>_<secret> (default prefix hmz). The key id is
public and finds the stored entry; the secret carries over 256 random bits
and only its SHA-256 hash is stored, so a leaked configuration or database
holds no usable key. Create a key once and hand Value to the client:
var key = ApiKey.Create(); // key.Value for the client, shown once
// store key.KeyId and key.SecretHash
The default store reads Authentication:ApiKeys (validated on start; keep
the values in the secret store, not in source control):
{ "Authentication": { "ApiKeys": { "Keys": {
"<keyId>": { "ClientId": "billing-worker", "SecretHash": "<64 hex>", "ExpiresAt": null }
} } } }
Rotate by adding the new key beside the old one, switching the client, then
removing the old entry. Register your own IApiKeyStore before AddApiKey()
to keep keys in a database.
builder.Services.AddAuthentication(/* the user scheme stays the default */)
.AddApiKey();
builder.Services.AddAuthorizationBuilder().AddInternalApiPolicy();
builder.Services.AddOpenApi(options => options.AddApiKeySecurity());
app.MapGroup("/internal").RequireInternalApiKey();
A request without the App-Api-Key header gets no result, so other schemes
still run; a malformed, unknown, expired or wrong key fails. Application
headers carry no X- prefix (deprecated by RFC 6648); another name is set
with AddApiKey(options => options.HeaderName = "...") and the same name
passed to AddApiKeySecurity(headerName: ...). The principal's
sub and name are the client id and api_key_id holds the key id for audit
logs. In an application that also signs in users, keep the user scheme as
the default: then a key only reaches endpoints that require the InternalApi
policy. In a service where the key is the only scheme, make it the default
and pass allProtectedOperations: true to AddApiKeySecurity.
To give a client more claims (roles, permissions), derive from
ApiKeyIdentityResolver, call the base and add claims, and register it as
IApiKeyIdentityResolver (before AddApiKey(), or replace the registration
afterwards). The resolver is asynchronous, so it can load the client's grants
from a database.
Permission authorization
Hmz.Core.SharedKernel.Authorization provides transport-neutral permission
contracts. Keep ICurrentUser focused on identity and populate a
request-scoped IPermissionSnapshotAccessor from application data after the
external identity has been resolved.
var snapshot = new PermissionSnapshot(
userId,
permissions.ToHashSet(StringComparer.Ordinal),
userPermissionStamp,
rolePermissionStamps);
permissionSnapshotAccessor.Set(snapshot);
PermissionChecker grants an exact permission or a deliberately configured
wildcard such as USER-MANAGEMENT.ROLES.*. Missing and empty snapshots deny
access. Applications should combine permissions from every assigned role
before constructing the snapshot.
The ASP.NET Core integration is under
Hmz.Core.SharedKernel.Http.Authorization:
services.AddPermissionAuthorization();
endpoint.RequirePermission(UserManagementPermissions.Roles.Manage);
Combine permissions with AND and OR through PermissionRule. A permission
code converts to a rule implicitly; each RequirePermission... call adds one
requirement and every requirement must pass, so chained calls are AND:
endpoint.RequireAllPermissions(Users.Read, Brands.Read); // A and B
endpoint.RequireAnyPermission(Product.Read, Product.Manage); // A or B
endpoint.RequireAnyPermission(Quotes.Approve, // A or (B and C)
PermissionRule.All(Quotes.Manage, Prices.Read));
endpoint.RequirePermission(Users.Read).RequirePermission(Brands.Read); // A and B
// Outside endpoints, against the current snapshot:
if (permissionChecker.Satisfies(PermissionRule.Any(Product.Read, Product.Manage))) { ... }
Rules validate their codes when built, render as text (A or (B and C)) for
documentation, and add PermissionRuleMetadata to the endpoint. Prefer a
dedicated permission over deep nesting when a combination describes a real job.
Use application-owned constants at endpoints rather than string literals.
Declared access
Every endpoint says on purpose who may call it: AllowAnonymous(), a permission (RequirePermission...), or RequireSignedInUser() for endpoints that any signed-in user may call (option lists, the caller's own data). A bare RequireAuthorization() looks the same as an endpoint whose permission was forgotten, so it does not count. One functional test keeps it that way:
var source = factory.Services.GetRequiredService<EndpointDataSource>();
EndpointAccess.FindUndeclared(source, "/api/v1/commerce").Should().BeEmpty();
A named policy (RequireAuthorization("api-key")) needs a marker next to it: metadata that implements IEndpointAccessMetadata and describes the rule in AccessDescription. Register options.AddOperationTransformer<EndpointAccessOperationTransformer>() to append the rule to each OpenAPI operation description (Access: Requires permission CATALOG.PRODUCTS.READ.); EndpointAccess.Describe(metadata) returns the same line for other documentation, such as MCP tool descriptions.
Resource policies (resource- and attribute-based rules)
Permission checks answer "may this user do this kind of action at all". A resource policy answers "may this user do it to this record", combining the permission snapshot with the record (author, owner, status, amount) and the current user. Write one policy per resource type, in the feature folder of the use case that owns the resource:
public sealed class StoryPostPolicy(IPermissionChecker permissions, ICurrentUser user)
: IResourcePolicy<StoryPost>
{
public ValueTask<AccessDecision> EvaluateAsync(StoryPost post, string action, CancellationToken ct) =>
ValueTask.FromResult(action switch
{
StoryPostActions.Delete when post.AuthorId == user.UserId => AccessDecision.Allow(),
StoryPostActions.Delete when permissions.Satisfies(Feeds.Moderate) => AccessDecision.Allow(),
StoryPostActions.Delete => AccessDecision.Deny("Only the author or a moderator.", StoryErrorCodes.NotAuthor),
_ => AccessDecision.DenyUnknownAction(action),
});
}
services.AddResourcePolicy<StoryPost, StoryPostPolicy>();
// In a handler, a bot command or a background job:
var decision = await access.CheckAsync(post, StoryPostActions.Delete, ct);
if (!decision.Allowed) return Result.Failure(decision.ToError(StoryErrorCodes.NotAuthor));
- Child resources check their parent first:
AccessDecision.AllAsync(() => access.CheckAsync(comment.Post, "read", ct), () => OwnRules(comment))stops at the first denial. IResourceCapabilities<TResource, TCapabilities>returns what one record allows (for exampleCanEdit,CanReadCost). Query handlers use it to mask response fields, and clients use it to show actions.- Business invariants that hold for every actor (status transitions, totals,
separation of duties written into business law) belong in the domain model.
Policies decide only who may act. A long
actionswitch usually means status rules sit in the policy instead of the aggregate. Dispatch each action to a private method, and split a policy per action only when one action grows large. - Lists are filtered in the database (data scopes and named query filters), never row by row through a policy.
IAuthorizationService.AuthorizeAsync(user, resource, new ResourceActionRequirement(action))evaluates the same policy.IAccessDecisionObserverreceives every decision, for audit logs. Permission catalogs, role assignments, persistence, cache invalidation, and version-stamp resolution remain responsibilities of the owning application. Do not make JWT permission claims or a claims transformer the application permission source of truth.
Advanced search
Hmz.Core.SharedKernel.AdvancedSearch provides a validated, allow-listed query pipeline. Clients never supply raw Dynamic LINQ. Search values reach the database as parameters (UseParameterizedNamesInDynamicQuery), so EF Core reuses one compiled query per search shape instead of compiling one per value.
services.AddAdvancedSearch();
A feature owns its ISearchConfiguration, source query, projection, and optional external resolvers:
public ValueTask<PagedResponse<ProductListItem>> ExecuteAsync(
AdvancedSearchRequest request,
CancellationToken cancellationToken = default) =>
advancedSearch.ExecutePageAsync(
dbContext.Products.AsNoTracking(),
product => new ProductListItem(product.Id, product.Name, product.Price),
request,
ProductSearchConfiguration.Instance,
cancellationToken: cancellationToken);
The projection overload projects the source query before applying filters,
global search, ordering, counting, and paging. Therefore, MatchKey resolves
against the projected result type, not the persistence entity. This supports
client-facing field names, renamed fields, SmartEnum .Value members, and
aggregate values exposed by the projection while keeping the query
provider-translatable.
Important behavior:
- fields inside one global-search item are OR-ed;
- separate search items use the requested
SearchLogic; - filters default to AND;
- multiple positive values inside one filter are OR-ed;
- negative multi-value operators are AND-ed;
- external no-match results remain match-nothing;
- default ordering should end with a unique field;
- validation errors use exact request paths;
- scalar conversion and enum parsing use bounded, safe messages.
- filter
searchValuesaccepts JSON strings or numbers and normalizes both forms before typed validation.
SearchFieldDefinition.AllowedOperators takes a collection expression
(AllowedOperators = [SearchOperator.Eq, SearchOperator.Contains]) and keeps
the values in a frozen set.
TODO: Consider optimizing multi-value scalar equality filters to an SQL
IN-style value-collection Contains expression (and NOT IN for negative
filters). Keep the current expanded equality clauses as the compatibility
baseline until translation is verified across supported EF Core providers and
projection shapes.
AdvancedSearch.OpenApi supplies reusable metadata and a schema transformer. Endpoint-specific examples remain in the API feature that owns the search contract.
EF Core data support
Hmz.Core.SharedKernel.Data includes:
- auditable, soft-deletable, and row-version entity bases;
EfRepositoryBase<T>;IUnitOfWorkandEfUnitOfWork;- entity-configuration helpers;
- audit, soft-delete, and domain-event interceptors.
Repository mutation methods may only update the DbContext change tracker. Commit through the owning module's unit of work:
await repository.AddAsync(entity, cancellationToken);
await unitOfWork.SaveChangesAsync(cancellationToken);
Keep provider-specific constraint interpretation and cross-context transaction policy in application Infrastructure.
EntityTypeConfigurationBuilderBase<TEntity, TId> configures row versions, soft delete (with the named filter) and audit columns for the interfaces an entity implements; derive every configuration from it and add only the entity's own mapping. Two helpers cover what remains common:
builder.Property(product => product.Status).IsRequired().HasSmartEnumConversion(); // stored as its value
builder.HasIndex(product => product.Sku).IsUnique().WhereNotDeleted(); // a deleted row frees the SKU
HasSmartEnumConversion<TEnum, TValue>() covers Smart Enums whose value is not an int.
A partial index over some Smart Enum members uses WhereIn, which writes "Status" IN (1, 2, 3) from the property's mapped column and the members' values. Configure the property before the index. WhereIn and WhereNotDeleted combine with AND in either order:
builder.HasIndex(rfq => rfq.Code).IsUnique() // at most one open version per code
.WhereIn(rfq => rfq.Status, RfqStatus.Draft, RfqStatus.AwaitingQuote, RfqStatus.Quoted)
.WhereNotDeleted();
A required column added to a table that already has rows needs a default for those rows, while the application keeps setting the value on every insert:
builder.Property(item => item.PublicId).HasDatabaseGeneratedUuid(); // gen_random_uuid(): a distinct key per existing row
builder.Property(item => item.SortOrder).HasBackfillDefault(0); // the app's 0 is stored as is
builder.Property(item => item.ImportedAt).HasBackfillDefaultSql("now()");
HasDatabaseGeneratedUuid() (PostgreSQL 13+) lets the database generate a key the application left as Guid.Empty; backfillOnly: true always sends the application's value. HasBackfillDefault and HasBackfillDefaultSql set IsRequired, the default and ValueGeneratedNever, so EF Core never takes a CLR default such as 0 for "let the database decide"; the default only fills the existing rows when the migration adds the column.
Every query filter is named. A specification can bypass single filters with Query.IgnoreQueryFilters([names]) (from Data.Specifications); the others still apply. Ardalis' parameterless IgnoreQueryFilters() still drops all of them. EfRepositoryBase<T> evaluates specifications with HmzSpecificationEvaluator, which applies the named form for lists, projections, CountAsync and AnyAsync:
public sealed class DeletedNotesSpecification : Specification<Note>
{
public DeletedNotesSpecification() =>
Query.IgnoreQueryFilters([QueryFilterNames.SoftDelete]).Where(note => note.IsDeleted);
}
The filter name belongs to whoever declares the filter: QueryFilterNames for SharedKernel's own, an application constant for its data scopes.
Named query filters and data scopes
The soft-delete filter is named QueryFilterNames.SoftDelete. Applications add their own named filters for an interface, once, and SharedKernel applies them to every root entity type that implements it:
modelBuilder.ApplyQueryFilter<IBrandOwned>(
"Brand",
owned => !BrandScopeEnforced || owned.BrandId == ActiveBrandId);
Read request state from the DbContext (its own members, or an interface it implements): EF Core swaps that reference for the running context on each query, while any other captured value is frozen into the cached model.
Data.Scoping describes a partition such as a tenant or brand: IDataScope<TKey> is the request scope (IsEnforced, ScopeId), IDataScopeKind<TKey> names the filter and key property, and an entity implements IScopedEntity<TScope, TKey> once per scope it belongs to. DataScopeWriteGuardInterceptor<TScope, TKey> refuses to save a scoped entity outside the enforced partition (DataScopeViolationException); register it before the audit, soft-delete and domain-event interceptors.
Persistence errors
Use cases depend on the provider-neutral IPersistenceErrorClassifier from Data.Errors and its checks: IsUniqueViolation(ex, constraint?), IsForeignKeyViolation(ex, constraint?), IsStringTooLong, IsConcurrencyConflict and IsTransient. Register the PostgreSQL implementation once with services.AddPostgresPersistenceErrorClassifier(). Modules add constraint-specific checks as their own extension members (for example IsCollectionCodeUniqueViolation(ex)) rather than defining classifier interfaces.
Save interceptors
AuditableInterceptorBase and SoftDeleteInterceptorBase handle both SaveChanges and SaveChangesAsync. Derived interceptors override the before-save pair together, or the after-save pair together, and let ChangeTracker.Entries() run DetectChanges.
Demo data seeds through Data.Seeding: context.SeedIfEmptyAsync(() => samples) inserts only into an empty table (soft-deleted and other-scope rows count), and context.HasAnyRowsAsync<T>() guards seeds that build dependent rows. Reference data the application depends on is seeded item by item instead.
Validation helpers
Hmz.Core.SharedKernel.Validation has two layers.
Domain invariants throw for the named parameter and return the value for inline use:
Code = code.RequireWithMaxLength(MaxCodeLength, nameof(code)).ToUpperInvariant();
Description = description.OptionalWithMaxLength(MaxDescriptionLength, nameof(description));
BrandId = brandId.RequirePositive(nameof(brandId));
Strings: IsBlank, TrimToNull, TrimToNullWithLf (also turns every line ending into \n, for stored multi-line text), ToCodeKey (trimmed and upper-cased, separators kept; null stays null), ExceedsMaxLength (after trimming), RequireWithMaxLength, OptionalWithMaxLength. Clip(maxLength) shortens text that is recorded rather than validated (snapshots taken after a commit) and trims the cut end. TypedCodeNormalizer.Normalize(input, separators) removes separators and upper-cases a code a person typed, so abcde-fghjk equals ABCDEFGHJK. Numbers (any INumber<T>): RequirePositive, RequireNonNegative, RequireInRange, and for nullable values OptionalNonNegative, OptionalInRange. Decimals: HasAtMostDecimalPlaces(places) tells whether a fixed-scale column such as numeric(18,2) stores the value without loss (trailing zeros do not count, so 1.500m has at most 2).
Request validation returns a validation Error with the field target, or null when the value is valid, so a validator reports every field at once:
var validation = FieldErrors.Collect(
request.Sku.RequiredError(code, "sku", "SKU"),
request.Name.MaxLengthError(MaxNameLength, code, "name", "Name"),
request.WidthMm.NonNegativeError(code, "widthMm", "Width"));
if (validation.IsFailure)
return Result.Failure<ProductDetails>(validation.Errors);
Proportional split
Numerics.ProportionalSplit.Allocate(amount, keys, shares, decimals: 2) splits an amount by shares (fractions per key) into rounded parts that add up to the amount exactly, for example a discount over order lines or a freight cost over packages:
var shares = new Dictionary<Guid, decimal> { [a] = 1m / 3, [b] = 1m / 3, [c] = 1m / 3 };
var parts = ProportionalSplit.Allocate(100m, [a, b, c], shares); // a: 33.34, b: 33.33, c: 33.33
The rounding difference goes to the first key (AllocationRemainder.FirstKey) or, with AllocationRemainder.LargestRemainder, to the parts that lost most to rounding (Hamilton's method), which is fairer when shares are close. rounding: MidpointRounding.ToEven gives banker's rounding. Percent(part, whole) returns 0 for a zero whole; PercentOfShare(share) turns a fraction into a percentage.
Text folding and slugs
Hmz.Core.SharedKernel.Text folds accents and builds URL slugs the same way on every host, without culture, ICU or invariant globalization mode:
FoldLatinAccents()replaces each accented Latin letter (U+00C0–U+024F and U+1E00–U+1EFF letters whose NFD is an ASCII letter plus combining marks, andĐ/đ) with its ASCII letter in the same case, and leaves every other character as it is. It maps character by character from a fixed table and does not normalize, so a SQLtranslateover the same table gives the same result (for example a generated comparison-key column). Normalize decomposed (NFD) input to NFC first when it can occur.ToSlug()folds, drops combining marks, lower-cases ASCII letters and joins the remaining runs with one hyphen:Sofa "Đà Lạt" 2-chỗbecomessofa-da-lat-2-cho. The result matches^[a-z0-9]+(-[a-z0-9]+)*$or is empty.ToNameKey()is the comparison key for "same name" checks: it folds, upper-cases ASCII letters only (no culture rule), and turns each run of separators into one space, trimmed:Serenity-05,SERENITY 05andsérénity 05all giveSERENITY 05. The separators are exactly the PostgreSQL bracket expression[ \t\n\r\u00A0\u2000-\u200A\u202F\u205F\u3000._/-], so a generated column can reproduce the key withbtrim(regexp_replace(translate(name, <fold table plus a-z>, <ASCII upper case>), '<separators>+', ' ', 'g'), ' '). The application owns that SQL and a test that compares it withToNameKeycharacter by character; any change to the fold, the case rule or the separators is a breaking change that needs a migration of such a column.
NameVariants handles "model + variant" names such as SERENITY 05, BLOOM 01 and JADE B:
NameVariants.FamilyBase("Serenity 05"); // "Serenity"
NameVariants.Suggest("Serenity 05", takenKeys, max: 3); // ["Serenity 07"] when 01..06 (and 1000) are taken
NameVariants.Suggest("jade b", ["JADE A", "JADE B"], 3); // ["jade 02", "jade C"]
FamilyBase drops one trailing variant (ASCII digits or one ASCII letter after separators); a name without one is its own base. Suggest takes the keys in use (ToNameKey by default, or the key you pass) and writes suggestions with the typed base: the number after the highest used, padded to the family's most common width (02 when there is no number yet), then the next free letter when the family uses letters.
Request validation
Validation runs request-shape checks before a handler, without tying them to a dispatcher. A validator lists field checks; every failure of every validator is returned at once, each with its target:
public sealed class CreateCollectionCommandValidator : RequestValidator<CreateCollectionCommand>
{
protected override IEnumerable<Error?> Validate(CreateCollectionCommand request) =>
[
request.Code.RequiredError(Codes.Invalid, "code", "Collection code"),
request.Code.MaxLengthError(Collection.MaxCodeLength, Codes.TooLong, "code", "Collection code"),
];
}
services.AddRequestValidatorsFromAssemblies(typeof(CreateCollectionCommand).Assembly);
services.AddMediator(options =>
options.PipelineBehaviors = [typeof(RequestValidationBehavior<,>)]);
IRequestValidator<TRequest> is asynchronous, so a validator can await a service when it must; checks that need the database (existence, uniqueness) still belong in the handler, and invariants in the domain. RequestValidationBehavior<,> (Messaging.Validation) is the Mediator adapter: it calls IRequestValidation and returns the failure as the handler's Result/Result<T> (built with ResultFailures). A custom dispatcher calls IRequestValidation.ValidateAsync(request, ct) the same way.
Smart Enum JSON
Serialization.SmartEnums is opt-in: an application without Smart Enums never calls it. options.AddSmartEnumConverters() adds one SmartEnumJsonConverterFactory that converts every Smart Enum as its value (SmartEnumJsonFormat.Name writes names). New Smart Enums need no registration. Call it on every JsonSerializerOptions that serializes Smart Enums: the API contract, stored JSON columns and caches. Integration event payloads already include the factory, so a Smart Enum inside an event travels as its value with no attribute. Another value-object enumeration plugs in the same way, with its own JsonConverterFactory. To use another format for one type, add its converter before the factory or put [JsonConverter(typeof(SmartEnumNameJsonConverter<T, int>))] on the type or property. An unknown member or a token of the wrong type fails with a SafeJsonException that lists the accepted values (see the Problem Details section below).
options.AddHmzSmartEnumSchemas() on OpenApiOptions documents every Smart Enum with what it is written as (SmartEnumSchemaTransformer). It reads the format from the SmartEnumJsonConverterFactory in the app's Microsoft.AspNetCore.Http.Json.JsonOptions, so it cannot disagree with the wire, and adds no setting of its own. Value format: a reusable component { "type": "integer", "format": "int32", "enum": [1, 2, 3], "x-enum-varnames": ["Phone", "Zalo", "Email"], "description": "1 = Phone, 2 = Zalo, 3 = Email" } (a string value gives type: string; members are ordered by value). Name format: { "type": "string", "enum": ["Phone", "Zalo", "Email"] }. A request or response property is a $ref to the component, a nullable one is oneOf: [{ "type": "null" }, { "$ref": ... }] (what .NET 10 emits), and an array, List<T> or dictionary value gets the same schema inline as items / additionalProperties. A route or query parameter of a Smart Enum type with TryParse gets the schema too (it assumes TryParse accepts the same format as the JSON converter). x-enum-varnames and the description use member names; there is no display-name convention. Hmz.Core.Mcp builds its tool input schemas from the same document, so MCP clients now see the enum values. A type the serializer does not convert as a Smart Enum is left as it is.
Enum options
Contracts.EnumOptions builds the response of a Smart Enum options endpoint. EnumOptionCatalog.Create(key, options) sorts EnumOption(Value, Code, DisplayName, ShortDesc, SortOrder) items by SortOrder and adds a strong ETag hashed from the key and the content. EnumOptionCatalog<T>.Create(key, items) keeps the given order and hashes items that carry extra data, such as a count per option, so a changed count changes the ETag. Return the ETag with Cache-Control and answer a matching If-None-Match with 304. .ProducesCachedOptions<TOption>() documents such an endpoint: 200 with a TOption[], 304, the opaque ETag on both, and an optional If-None-Match. It adds no 401, so chain .ProducesAuthorizationProblems() on a protected endpoint. catalog.ToCachedOk(context) (namespace Http) writes the whole answer through EntityTagHttp.CachedOk (see HTTP boundary support).
State machines
StateMachines declares the lifecycle of an aggregate once, as a frozen transition table, instead of if (Status != ...) checks in each method. The state stays on the aggregate (an EF column with a private setter); the machine reads and writes it through accessors and owns nothing persistent. States and triggers are plain enums or Smart Enums.
public sealed class RequestForQuotation
{
public RfqStatus Status { get; private set; }
private IStateMachine<RfqStatus, RfqAction> Lifecycle =>
RfqLifecycle.Table.Bind(this, () => Status, status => Status = status);
public Result Submit() => Lifecycle.Fire(RfqAction.Submit);
public IReadOnlyList<AvailableAction<RfqAction>> AvailableActions() => Lifecycle.AvailableActions();
}
public static class RfqLifecycle
{
public static readonly TransitionTable<RequestForQuotation, RfqStatus, RfqAction> Table =
new TransitionTableBuilder<RequestForQuotation, RfqStatus, RfqAction>()
.Permit(RfqStatus.Draft, RfqAction.Submit, RfqStatus.AwaitingQuote,
"at least one line", rfq => rfq.LineItems.Count > 0)
.Permit(RfqStatus.AwaitingQuote, RfqAction.Approve, RfqStatus.Approved)
.Build(ErrorCode.Create(ErrorType.BusinessRule, "rfq-transition", "RFQ"));
}
Definition:
Permit(from, trigger, to, guardName?, guard?). A guard needs a name (and a name needs a guard); the name is the reason in the refusal and the label in the diagrams. A secondPermitfor the same (state, trigger) throwsArgumentException, so a definition cannot be ambiguous.Buildfreezes the (state, trigger) matrix and the triggers per state inFrozenDictionaryinstances.Runtime:
CanFire(trigger),Fire(trigger)andPermittedTriggers()(guard-aware, in declaration order). Aggregates depend onIStateMachine<TState, TTrigger>, so another engine can replace the table.Refusal:
Firereturns aResultfailure of typeErrorType.BusinessRule(HTTP 422,Error.BusinessRule) whose message names the state, the trigger and, when a guard refused, the guard name; the state does not change. No exception is thrown for an expected refusal. The error code is the one given toBuild(refusalErrorCode); without it,ErrorCode.Create(ErrorType.BusinessRule, "state-transition")(COM.RULE.STATE-TRANSITION, alsoTransitionTable<,,>.DefaultRefusalErrorCode). Give each aggregate its own module code.Available actions:
machine.AvailableActions()returnsAvailableAction<TTrigger>(Action, Name)items for anavailableActionsresponse field, so clients stop repeating the rules.Actionserializes like the trigger does elsewhere: an enum as the API configures it, a Smart Enum by value withAddSmartEnumConverters().Docs export:
table.ToMermaid()(stateDiagram-v2) andtable.ToDot()(Graphviz) list every transition with its guard asTrigger [guard name].Matrix test:
table.Matrix()lists every (state x trigger) of plain enums,table.Matrix(Status.List, Action.List)of Smart Enums (the cell order follows the lists you pass; order them when a snapshot depends on it), asTransitionMatrixEntry(From, Trigger, IsPermitted, To, GuardName); guards are named, not evaluated.MatrixText()gives one line per cell for a snapshot, so a test asserts the whole definition without a test-framework dependency:RfqLifecycle.Table.Matrix().MatrixText().Should().Be(ExpectedMatrix);
There is no Stateless adapter package in 0.1.20: no consumer needs a second engine yet, and an adapter would add a package dependency. IStateMachine is the seam where one can be added later without changing aggregates.
JSON helpers
Serialization.JsonElementExtensions.TryGetString(params names) returns the first of the named properties that holds a string, without throwing for other value kinds. JsonNamingExtensions.ToCamelCaseKey() converts a property name with JsonNamingPolicy.CamelCase.
Stored JSON and safe readers
Serialization.StoredJsonOptions.Create(configure?) gives the options for JSON an application stores or hashes: web defaults, compact, UnsafeRelaxedJsonEscaping, camel-case string enums and Smart Enums by value. They stay separate from the API wire options, so a wire change never changes stored data or hashes. Every call returns a new instance and JsonSerializerOptions caches metadata, so keep one per module (static readonly or a singleton); configure runs last to add converters.
public static readonly JsonSerializerOptions Stored = StoredJsonOptions.Create(o => o.Converters.Add(new MyConverter()));
Non-throwing readers, next to TryGetString:
element.TryGetScalarText("sku", out var sku); // string, or a number as its raw text; false for anything else
element.TryGetId(out var id); // the "id" property, same rules (CMS ids are strings or numbers)
var settings = JsonObjects.ParseOrEmpty(row.SettingsJson); // blank, invalid or non-object text gives {}
var none = JsonObjects.Empty(); // a detached {}
JsonScalar.IsScalar("\"red\"", maxLength: 50); // string, number, true or false; not null, objects or arrays
Serialization.JsonPaths reads and writes JsonNode trees by dotted path. a[].b collects b from every item of a on read, and on write spreads a list into [{ "b": v1 }, { "b": v2 }]:
JsonPaths.Read(node, "price.amount"); // the node, or null when missing
JsonPaths.Read(node, "variants[].sku"); // ["A","B"]: items without a value are skipped
JsonPaths.Set(target, "seo.title", JsonValue.Create("Hi"));
JsonPaths.Set(target, "variants[].sku", new JsonArray("A", "B"));
A path with an empty segment (a..b, .a, a.) or a bare [] segment is malformed: Read returns null, Set throws ArgumentException. Set stores the value node as given (pass DeepClone() when it already has a parent) and replaces a non-object found on the way.
HTTP boundary support
Hmz.Core.SharedKernel.Http currently provides:
- Result-to-Problem-Details mapping;
- validation problem results;
- global and request-body exception handlers;
- strong ETag parsing/formatting;
- precondition results and conditional-request OpenAPI helpers;
ProducesAuthorizationProblems(), which documents the 401 and 403 problem responses of a protected endpoint;[OpenApiDeprecated]on a request or response property, which marks itdeprecated: trueonceoptions.AddSchemaTransformer<DeprecatedPropertySchemaTransformer>()is registered (properties typed as a shared$refcomponent are left alone). The attribute targets properties only, so on a positional record write[property: OpenApiDeprecated];- streamed single-file multipart uploads and file-signature detection
(
Http.Uploads).
These types use ASP.NET Core and belong only at HTTP boundaries. Domain and UseCase projects should remain transport neutral.
ETags use quoted invariant row versions such as "42". Clients should treat the complete quoted value as opaque and return it unchanged through If-Match or If-None-Match.
RequiresStrongIfMatch(), ProducesStrongEntityTag(statusCodes) and SupportsIfNoneMatch() document row versions only: their header pattern is "[0-9]{1,10}", whatever the name suggests. A generated client rejects a hash or composite tag documented with them, so use the opaque helpers below for those.
A composite resource or option list has no single row version, so its ETag is an opaque strong tag computed from its content: ContentEntityTag.Create(key, value, serializerOptions) (namespace Contracts, transport neutral, so a query can compute it) returns "{key}-{SHA-256 lower-case hex}" of the value's JSON. Pass the serializer options the endpoint writes the body with; EnumOptionCatalog uses the same tag. Recompute it from the current state and check a write with EntityTagHttp.HandleIfMatch(context, currentEntityTag), which returns 428 when If-Match is missing, a validation problem when it is weak, *, a list or malformed, 412 when it differs, and null when the write may proceed. When the tag comes from state the endpoint must load first, use EntityTagHttp.HandleIfMatchAsync(context, loadCurrent, currentEntityTag, ct): it reads If-Match before loadCurrent runs (so 428 and the validation problem cost no load), maps a failed load through ToProblem, answers 412 on a mismatch, and otherwise returns an IfMatchResolution<T> whose Current is the loaded state:
var precondition = await EntityTagHttp.HandleIfMatchAsync(
context,
ct => sender.Send(new GetCurrentUserProfileQuery(userId), ct),
profile => ContentEntityTag.Create("profile", profile, serializerOptions),
cancellationToken);
if (!precondition.Passed)
return precondition.Problem;
var expectedRowVersion = precondition.Current.RowVersion; // not null once Passed
Document it with RequiresOpaqueIfMatch(), ProducesOpaqueEntityTag(statusCodes) and SupportsOpaqueIfNoneMatch(); the Strong helpers document only digit row versions.
The version travels only in the ETag header:
- Response bodies carry no row version. A response record that needs it for
WriteStrongkeeps it off the wire, for example[property: JsonIgnore] uint RowVersion. - Search and list responses carry no version. A client reads the single record (a
GETby id that returns the ETag) before it edits, then sends that ETag asIf-Match. - Browser clients on another origin can read the header only when the CORS policy exposes it:
WithExposedHeaders(HeaderNames.ETag, HeaderNames.Location, HeaderNames.ContentDisposition). If a client cannot see the ETag, fix the exposed headers; never copy the version into the body.
A cacheable read (settings, option lists, a composite view) answers with EntityTagHttp.CachedOk(context, entityTag, value, maxAge?, sharedCache: false): Cache-Control: private, max-age=300, must-revalidate (EntityTagHttp.DefaultCacheMaxAge), 304 with the same Cache-Control for a matching If-None-Match, a validation problem for an invalid one, and otherwise 200 with the value and the ETag. Pass sharedCache: true (public) only for data that is the same for every caller, so shared caches may store it; private is the default because most authenticated responses depend on the caller. Document one object with .ProducesCachedObject<T>() and a list with .ProducesCachedOptions<T>().
Register the shared Problem Details behavior in an API host:
services.AddHmzProblemDetails();
Malformed request binding is sanitized. Only messages represented by Serialization.SafeJsonException may expose bounded actionable details.
AddHmzProblemDetails also sets RouteHandlerOptions.ThrowOnBadRequest = true, so a Minimal API binding failure is thrown in every environment and answered by RequestBodyExceptionHandler (without it only Development throws and the other environments answer a bare 400 with an empty body). A binding failure is a 400 application/problem+json with errors.request holding the safe message (or The request is invalid.). A safe converter error also carries the target extension, the same name as the business-rule problems: the JSON property of JsonException.Path ($.reason gives reason, $.items[0].kind gives items[0].kind); a non-safe error has no target. Any other BadHttpRequestException (413, 415, ...) keeps its own status with a plain problem (title from the status, no errors, no framework message). The Smart Enum converters throw SafeJsonException: '99' is not a valid RfqLostReason value. Accepted values: 1, 2, 3. (at most 20 members, then …; the echoed client value is cut at 64 characters), A RfqLostReason value must be a JSON number. and, in the name format, ... name must be a JSON string.
To opt out, call services.Configure<RouteHandlerOptions>(o => o.ThrowOnBadRequest = false) after AddHmzProblemDetails() (the later registration wins).
Every client binding error is now an exception. An app whose UseExceptionHandler records the diagnostics of each handled exception (SuppressDiagnosticsCallback = _ => false) would log each one as an error and count it in its error metrics. HmzExceptionDiagnostics.SuppressClientErrors is the callback that keeps them out: it suppresses a handled BadHttpRequestException with a status below 500 and records everything else.
app.UseExceptionHandler(new ExceptionHandlerOptions
{
SuppressDiagnosticsCallback = HmzExceptionDiagnostics.SuppressClientErrors
});
Streamed file uploads
MultipartUploads.ReadSingleFileAsync reads a multipart/form-data request
without buffering it and hands the first file section to a callback. The
section content is a BoundedReadStream that throws UploadTooLargeException
one byte past MaxFileBytes, so oversized files fail instead of being
truncated.
app.MapPost("files", (HttpContext context, ISender sender, CancellationToken ct) =>
MultipartUploads.ReadSingleFileAsync(
context,
new MultipartUploadOptions(maxFileBytes),
async (file, token) =>
{
var result = await sender.Send(
new UploadFileCommand(file.Content, file.FileName, file.DeclaredLength),
token);
return result.IsFailure ? result.ToProblem(context) : TypedResults.Ok(result.Value);
},
ct))
.DisableAntiforgery();
| Condition | Response | Code |
|---|---|---|
Not multipart/form-data |
415 problem | http.upload-unsupported-media-type |
| Missing/invalid boundary, truncated or malformed body | 400 validation problem (request) |
http.upload-invalid-boundary, http.upload-malformed |
Content-Length above MaxFileBytes + MultipartHeadroomBytes (default 1 MiB), file above MaxFileBytes, or any UploadTooLargeException from the callback |
413 problem | http.upload-too-large |
| No file section | 400 validation problem keyed by FileField |
http.upload-file-required |
Rules:
- The callback must consume
Contentbefore returning. FileNameandContentTypeare client-supplied: detect the real type from content and never use the name as a storage path.- Application exceptions may derive from
UploadTooLargeException(for example a per-purpose limit enforced after storage) and still map to 413. - Other exceptions, including storage
IOExceptions, propagate to the global exception handler.
File signatures
FileSignatures.Detect recognizes a file from its leading bytes, so the stored
content type never comes from the client. It returns a DetectedFileType
(Extension, ContentType, IsImage, IsVideo) or null:
| Content | Extension | Content type |
|---|---|---|
JPEG (FF D8 FF) |
.jpg |
image/jpeg |
PNG (89 50 4E 47 0D 0A 1A 0A) |
.png |
image/png |
WebP (RIFF + size + WEBP) |
.webp |
image/webp |
PDF (%PDF-) |
.pdf |
application/pdf |
MP4 (ftyp box with a video major brand such as isom, mp42, avc1) |
.mp4 |
video/mp4 |
QuickTime (ftyp box with major brand qt ) |
.mov |
video/quicktime |
WebM (EBML header with DocType webm) |
.webm |
video/webm |
HEIF/AVIF images and M4A audio share the ftyp container but have other
brands, so they are not reported as video; other Matroska files are not WebM.
Read FileSignatures.PrefixLength (64) bytes, because the WebM DocType sits
inside the EBML header.
var prefix = new byte[FileSignatures.PrefixLength];
var length = await content.ReadAtLeastAsync(prefix, prefix.Length, throwOnEndOfStream: false, ct);
var detected = FileSignatures.Detect(prefix.AsSpan(0, length));
if (detected is not { IsImage: true })
return Errors.UnsupportedFile();
The type has no ASP.NET Core dependency, so UseCase code may use it. Which
types an upload accepts, and the messages for rejected files, stay application
policy. FileSignatures.IsImage(contentType) and FileSignatures.IsVideo(contentType)
re-check a stored content type.
Additional dependencies
The current package references Mediator abstractions, ASP.NET Core/OpenAPI, EF Core (including EF Core Relational for messaging persistence), Npgsql (PostgreSQL error classification), System.Linq.Dynamic.Core, and temporary Ardalis building blocks for guards, shared entities, specifications, SmartEnum, repositories, and service introspection. Versions are centrally managed in Directory.Packages.props.
Build, test, and pack
dotnet build Hmz.Core.SharedKernel/Hmz.Core.SharedKernel.csproj `
--configuration Release
dotnet run `
--project tests/Hmz.Core.SharedKernel.UnitTests/Hmz.Core.SharedKernel.UnitTests.csproj `
--configuration Release `
--no-build `
-- --minimum-expected-tests 1
dotnet pack Hmz.Core.SharedKernel/Hmz.Core.SharedKernel.csproj `
--configuration Release `
--output <package-output>
Current version: 0.1.17, prepared for NuGet publication. Inspect the package before
publishing and never republish the same version; advance the project version
and changelog for any subsequent package-content change.
Extension rules
- Add only cross-project contracts with demonstrated reuse.
- Keep feature-specific models and policies in the owning application.
- Keep HTTP and EF Core dependencies in their explicit namespaces and out of Domain code.
- Add tests for compatibility-sensitive behavior and public contracts.
- Preserve existing comments; add or update comments only when behavior changes make them inaccurate or clarification is important.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. 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. |
-
net10.0
- Ardalis.GuardClauses (>= 5.0.0)
- Ardalis.ListStartupServices (>= 1.1.4)
- Ardalis.SharedKernel (>= 5.0.0)
- Ardalis.SmartEnum (>= 8.2.0)
- Ardalis.Specification (>= 9.3.1)
- Ardalis.Specification.EntityFrameworkCore (>= 9.3.1)
- Mediator.Abstractions (>= 3.0.2)
- Microsoft.AspNetCore.OpenApi (>= 10.0.11)
- Microsoft.EntityFrameworkCore (>= 10.0.11)
- Microsoft.EntityFrameworkCore.Relational (>= 10.0.11)
- Microsoft.OpenApi (>= 2.12.2)
- Npgsql (>= 10.0.3)
- System.Linq.Dynamic.Core (>= 1.7.4)
NuGet packages (3)
Showing the top 3 NuGet packages that depend on Hmz.Core.SharedKernel:
| Package | Downloads |
|---|---|
|
Hmz.Core.Notifications
In-app notification engine for Hmz backends on EF Core and PostgreSQL: deduplicated per-recipient store, audience and scope rules, REST endpoints, live signals through Hmz.Core.Realtime after commit and retention. |
|
|
Hmz.Core.Mcp
Exposes Minimal API endpoints as permission-filtered MCP tools by re-dispatching each call through the application's own HTTP pipeline. |
|
|
Hmz.Core.Realtime
Reusable realtime delivery engine for Hmz backends on ASP.NET Core: a best-effort publisher, an in-process backplane and one multiplexed server-sent events stream per client, each replaceable by an adapter package. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.1.21 | 106 | 11/17/2026 |
| 0.1.20 | 86 | 11/16/2026 |
| 0.1.19 | 130 | 11/8/2026 |
| 0.1.18 | 123 | 11/1/2026 |
| 0.1.17 | 139 | 10/21/2026 |
| 0.1.16 | 108 | 10/19/2026 |
| 0.1.15 | 101 | 10/13/2026 |
| 0.1.14 | 106 | 10/9/2026 |
| 0.1.13 | 99 | 10/9/2026 |
| 0.1.13-pre03 | 95 | 10/9/2026 |
| 0.1.13-pre01 | 92 | 10/9/2026 |
| 0.1.12 | 101 | 10/8/2026 |
| 0.1.11 | 387 | 9/26/2026 |
| 0.1.10 | 140 | 9/21/2026 |
| 0.1.9 | 147 | 9/12/2026 |
| 0.1.8 | 145 | 9/7/2026 |
| 0.1.7 | 151 | 5/8/2026 |
| 0.1.6 | 141 | 5/7/2026 |
| 0.1.5 | 131 | 5/6/2026 |
| 0.1.4 | 134 | 4/23/2026 |