ASP.NET Core
Cancel appointment 100 in the right organization
Keep HTTP and background scheduling operations tenant-safe without making every caller reconstruct membership, storage or cleanup.
Published · AI disclosure
Alex cancels North Care’s appointment 100, then switches to South Health, which also owns appointment 100. The API must select the right row without asking every endpoint to reconstruct tenant authorization.
An export can run after the request ends or membership changes. It needs the same ownership rule but cannot borrow the request’s scope or its earlier permissions.
The retained independent run of the pinned .NET 10 fixture passed 79 SQLite and loopback HTTP checks. A fresh extraction compiled, but its self-test timed out before reporting a result. This guide does not establish SQL Server behavior, durable jobs, production authentication or native database interruption.
One ownership rule, two consumers
CareLedger is a fictional scheduling SaaS. North Care and South Health are tenant organizations; their facilities narrow access. Alex can schedule for North and read South. Blair can edit only North outpatient slots.
- The route selects an organization; current membership supplies permission.
- A background job may run after its HTTP request ends or its requester loses access.
- Authorize at HTTP request admission and each job execution; own scoped data and cleanup on every exit.
The authority is the verified identity plus the application’s membership directory, tenant activity and stored job request. An identity-provider tenant ID needs an explicit mapping. Neither a route value nor a job ID grants access.
Here an operation means one request or job execution. Calls within a request share its immutable snapshot. Revocation affects the next operation; stricter in-flight revocation requires another policy.
Choose what the consumer should have to know
Put recurring obligations where callers can rely on them.
- Explicit inputs on each use-case call: Pass an organization selector and verified actor. The use case owns authorization and storage. Portable across hosts, but every call carries transport authority inputs.
- Expose an authorization value and context factory: Resolve grants, open storage, enforce facility/operation rules and remember cleanup. Useful inside the data module; exposes the wrong responsibilities to HTTP and job consumers.
- Scoped HTTP services + a bounded job operation: Call a scheduling method or execute a registered job ID. Host must install admission correctly; the application module owns authorization and lifetime.
Choose scoped HTTP application services and one export-job boundary. Calls stay small, with shared setup at admission. The trade-off is host-specific wiring: middleware order and scope binding are prerequisites. A non-HTTP host needs its own admission adapter.
The admission requirement is deliberate: resolving an application service without validated tenant access fails closed. Tenant switching starts another operation. There is no mutable current-tenant setter or generic delegate runner.
Does that require a database per organization?
Assume 30 organizations, one schema, one permitted region, two platform engineers and no independent restore commitment. Shared SQL Server is provisional: workload skew, latency/availability targets and the required isolation threat model can change placement.
Storage changes operational obligations, not the consumer contract.
- Shared database: One schema rollout per placement. Every path must preserve row ownership; capacity and database recovery are shared.
- Database per tenant: Separate principals and database restore units. Trusted routing, connection pools, backups and versioned migrations become fleet operations.
- Hybrid: Dedicated placement for organizations with distinct requirements. Operate both models and enforce a write fence during tenant moves.
Independent restore or regional placement can favor dedicated databases. It still cannot repair a wrong cache key or file authorization check. The runnable sample uses shared SQLite; SQL Server behavior needs its own evidence. Storage tradeoffs.
The endpoint asks to change an appointment
An HTTP consumer supplies the appointment and intended change. It receives Appointments from DI; tenant selection, permissions, storage and disposal do not become endpoint parameters. These are the actual sample lines:
api.MapPatch("/appointments/{id:int}", async (int id, ChangeStatus input, Appointments appointments, CancellationToken ct) =>
ToHttp(await appointments.ChangeStatusAsync(id, input.Status, ct)));The service returns ChangeOutcome: Changed, NotFound, Invalid or Forbidden. ToHttp maps that application result to HTTP. The operation validates the change, authorizes the facility and owns the write and cache invalidation:
public async Task<ChangeOutcome> ChangeStatusAsync(int id, string status, CancellationToken cancellationToken)
{
if (!_access.CanWrite) return ChangeOutcome.Forbidden;
if (status is not ("scheduled" or "cancelled")) return ChangeOutcome.Invalid;
var row = await _db.Appointments.SingleOrDefaultAsync(
a => a.Id == id && _access.Facilities.Contains(a.FacilityId), cancellationToken);
if (row is null) return ChangeOutcome.NotFound;
row.Status = status;
await _db.SaveChangesAsync(cancellationToken);
_cache.Remove(_access, row);
return ChangeOutcome.Changed;
}Here _access is immutable authorization facts, _db is the request-owned context, and _cache is the tenant-qualified cache. Their constructors stay internal; the registration module supplies them.
The fixture proves sequential invalidation after a write. Commit/invalidation failures and concurrent cache repopulation are untested; stronger consistency needs a versioned-cache or coordinated invalidation design.
A result is materialized before the method completes. The public surface returns DTOs/outcomes rather than EF entities, IQueryable or a context that remains usable outside its operation.
Establish tenant access before resolving the service
The public hosting hooks install the internal registrations, admission middleware and endpoint marker. Authentication must already be registered. Their required order is visible:
builder.Services.AddCareLedgerScheduling(databasePath);
// Build the app after registering authentication and authorization.
app.UseRouting();
app.UseAuthentication();
app.UseCareLedgerTenantAccess();
app.UseAuthorization();
var api = app.MapGroup("/tenants/{tenant}").RequireCareLedgerTenant();A separate consumer assembly compiles these hooks without internal types. RequireCareLedgerTenant marks tenant endpoints and requires authentication; unmarked endpoints such as health checks do not need tenant access.
The internal IMiddleware adapter runs after routing/authentication, resolves current membership and installs TenantAccess as a request feature before calling the next component. It injects no data context. Middleware activation.
public async Task InvokeAsync(HttpContext http, RequestDelegate next)
{
if (http.GetEndpoint()?.Metadata.GetMetadata<TenantEndpoint>() is null) { await next(http); return; }
if (http.User.Identity?.IsAuthenticated != true) { await http.ChallengeAsync(); return; }
try
{
var selectedTenant = http.Request.RouteValues["tenant"]?.ToString() ?? "";
var subject = http.User.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrWhiteSpace(subject)) throw new TenantDeniedException();
var access = memberships.Resolve(subject, selectedTenant);
http.Features.Set(access);
await next(http);
}
catch (Exception error) when (!http.Response.HasStarted && error is TenantDeniedException or ExportJobRejectedException)
{
http.Response.StatusCode = StatusCodes.Status403Forbidden;
}
}The scoped access registration reads only the validated feature and fails if absent. ASP.NET owns context disposal; the endpoint creates no second scope. Await service calls sequentially: one request shares one context, which cannot run parallel operations. Context lifetime.
Admission maps missing membership/subject and downstream permission denials to 403 before a response starts. Unexpected lookup/configuration failures propagate without a fallback tenant. A denial after response start propagates; it cannot rewrite the response.
The companion’s X-Demo-User header intentionally impersonates fixtures. Production needs token signature, issuer, audience and lifetime validation plus application membership lookup. JWT validation.
The use-case boundary still needs correct database predicates
A global query filter supplies the tenant predicate for ordinary entity reads; the use case adds its facility predicate. Composite keys identify an appointment as (TenantId, Id). Its facility relationship includes the same tenant.
protected override void OnModelCreating(ModelBuilder model)
{
model.Entity<Facility>().HasKey(f => new { f.TenantId, f.FacilityId });
model.Entity<Facility>().HasQueryFilter(f => f.TenantId == _tenantId);
model.Entity<Appointment>().HasKey(a => new { a.TenantId, a.Id });
model.Entity<Appointment>().HasQueryFilter(a => a.TenantId == _tenantId);
model.Entity<Appointment>().HasOne<Facility>().WithMany()
.HasForeignKey(a => new { a.TenantId, a.FacilityId }).OnDelete(DeleteBehavior.Restrict);
model.Entity<FileRecord>().HasKey(f => new { f.TenantId, f.Id });
model.Entity<FileRecord>().HasQueryFilter(f => f.TenantId == _tenantId);
model.Entity<FileRecord>().HasOne<Facility>().WithMany()
.HasForeignKey(f => new { f.TenantId, f.FacilityId }).OnDelete(DeleteBehavior.Restrict);
}The row identifier alone does not establish ownership. The write predicate has to include the tenant as well as the appointment ID. Checking only a detached object’s displayed tenant is not a substitute for using the composite key on the database write.
Both SaveChanges paths also validate tenant, write permission and original/current facility values. Detached OriginalValues are not authorization evidence, so HTTP changes load the permitted resource first. Internal data access remains privileged. Composite relationships.
Query filters reduce missed predicates; they do not authorize callers or constrain every SQL command. The executable deliberately demonstrates IgnoreQueryFilters. Bulk and direct-SQL hazards are in the reference. Query filters.
A job cannot borrow yesterday’s request
Blair requests a North export, then loses membership before it runs. Copying the earlier authorization snapshot into the job would preserve expired authority. Store the request’s identity and scope, then revalidate them when executing.
The public contract is for trusted worker/in-process adapters, not user-facing execution endpoints. It reauthorizes the stored requester, not the invoking worker. JobId selects work; transport/caller authentication remains the adapter’s responsibility:
public interface IExportJobs
{
Task<ExportResult> ExecuteAsync(JobId id, CancellationToken cancellationToken);
}The boundary owns one awaited async DI scope. Its singleton captures only the framework’s scope factory; consumers never receive IServiceProvider or a callback that can escape the scope.
internal sealed class ExportJobs(IServiceScopeFactory scopes) : IExportJobs
{
public async Task<ExportResult> ExecuteAsync(JobId id, CancellationToken cancellationToken)
{
await using var scope = scopes.CreateAsyncScope();
try
{
return await scope.ServiceProvider.GetRequiredService<ExecuteScheduleExport>()
.ExecuteAsync(id, cancellationToken);
}
catch (TenantDeniedException) { throw new ExportJobRejectedException(); }
}
}Inside that scope, the executor loads the registered request, validates current tenant activity and membership, checks operation/facility permission, and owns a fresh context:
internal sealed class ExecuteScheduleExport(ExportRegistry registry, MembershipDirectory memberships, TenantDatabase database)
{
public async Task<ExportResult> ExecuteAsync(JobId id, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var request = registry.Get(id);
var access = memberships.Resolve(request.Subject, request.TenantId);
access.RequireWrite();
access.RequireFacility(request.FacilityId);
await using var db = database.CreateContext(access);
var count = await db.Appointments.Where(a => a.FacilityId == request.FacilityId)
.CountAsync(cancellationToken);
return new(access.TenantId, request.FacilityId, count);
}
}The result arrives after context and scope cleanup. Unknown IDs/current-access denials become public ExportJobRejectedException; cancellation propagates OperationCanceledException. Other faults propagate. The fixture schedules no retries; production must classify transient failures.
The internal factory binds validated TenantAccess to fresh storage. EF’s factory accepts cancellation, not an authorization argument; this adapter makes binding explicit without caching request facts in a singleton. EF factory contract.
BackgroundService supplies a shutdown token; it creates no automatic per-job scope. A worker loop can call this bounded operation. The companion exercises a deterministic executor, not a hosted queue. Background-service scopes.
Normal intake is ScheduleExports.RequestCountAsync: it returns a registered ID that remains usable after the request scope ends. This is in-memory fixture acceptance, not durable delivery; a trusted transport would hand that ID to IExportJobs.
The fixture restricts counts/exports to writers using CanWrite. Production can require an export-specific permission and purpose. Corrupted registry records are test-only; producer/broker authentication and durability remain unimplemented.
The HTTP CountSlotsAsync operation awaits the export before completing the request, propagates RequestAborted and removes its temporary registry entry on every exit. It produces a count, not an export file. Moving durable work to a queue would change cancellation and acceptance semantics.
Cancellation tests verify propagation through EF’s command pipeline and cleanup. They block an interceptor before native SQL; interrupting an in-flight query depends on the provider. EF cancellation guidance.
Retrying a stored ID creates fresh storage and rechecks membership. User-facing status/download routes must independently authorize their current caller; the worker contract is not that API.
Run the failure cases, then adapt one entry point
The runnable companion ZIP contains the complete source, locked dependencies and raw runs. Use SDK 10.0.101/runtime 10.0.1; the pins reproduce the experiment, not a production patch policy.
dotnet restore --locked-mode
dotnet build -c Release --no-restore
dotnet run -c Release --no-build --no-restore -- --self-testExpected: zero build warnings/errors, exit 0 and RESULT 79 checks passed. SQLite relational and loopback HTTP only. SQL Server not tested.
The checks reread complete foreign rows after attempted changes; exercise permission switches, detached attacks, files/cache and revoked jobs; and observe context/scope cleanup on failure and cancellation. Concurrent request/job consumers use distinct contexts.
Start --demo instead of --self-test for a loopback API. These two calls return 200 with different slot labels, despite the same ID:
curl -i -H "X-Demo-User: alex" http://127.0.0.1:5080/tenants/north/appointments/100
curl -i -H "X-Demo-User: alex" http://127.0.0.1:5080/tenants/south/appointments/100A PATCH of South-only ID 201 through North returns 404 and leaves South unchanged. A South write by Alex returns 403 because that membership is read-only. The README supplies the remaining commands; every run starts with fresh synthetic data.
For your next tenant-owned operation, establish its authority at ingress, keep permissions/data/lifetime inside its use case, and add a negative check against the actual infrastructure before enabling it. Provider testing strategy.
Take the checks into your own system
If changing North’s appointment 100 alters South’s row or a revoked member can still execute a queued export, the ownership boundary fails even if the request returned its expected status code.
The 22-use-case operational reference separates exercised SQLite behaviors from untested patterns for bulk writes, pooling, SQL Server, storage, recovery and other production concerns.
Under the same synthetic fixture, startup cleanup was verified after a real SQLite seeding failure, and request and worker cancellation were observed at EF’s command interceptor. This does not demonstrate that a provider aborts an already-running native query.