Skip to content

6.4. Minimal APIs

Mikołaj Milewski edited this page Nov 12, 2026 · 1 revision

ASP.NET Core Minimal APIs

Stateflows.Extensions.MinimalAPIs maps the events accepted by registered Stateflows behaviors to ASP.NET Core Minimal API endpoints. It also maps behavior discovery and lifecycle endpoints, typed Activity input/output pins, Entity field and projection endpoints, and custom endpoints declared in behavior definitions.

Map and configure the API

Install Stateflows.Extensions.MinimalAPIs, register the behaviors, then map the endpoints:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Stateflows;
using Stateflows.Extensions.MinimalAPIs;
using Stateflows.StateMachines;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddStateflows(stateflows => stateflows
    .AddStateMachines(machines => machines.AddStateMachine<Order>()));

var app = builder.Build();
app.MapStateflowsMinimalAPIsEndpoints(api => api
    .SetApiRoutePrefix("stateflows"));
app.Run();

The prefix defaults to stateflows; pass an empty string to map at the application root, taking care to avoid collisions. Endpoint definitions are built when MapStateflowsMinimalAPIsEndpoints runs. Its optional callback configures mappings generated from the behavior definitions already registered with the application.

Standard discovery and lifecycle endpoints

In the table, {prefix} is /stateflows by default, {name} is a behavior class name, and {instance} is a behavior instance ID. Route resource names use stateMachines, activities, actions, or entities.

Method and route Purpose
GET {prefix}/classes List behavior classes across registered behavior types.
GET {prefix}/ List stored behavior instance IDs across registered behavior classes.
GET {prefix}/classes/{resource} List classes of one type, e.g. classes/stateMachines.
GET {prefix}/{resource} List stored instances of one type, e.g. activities.
GET {prefix}/{resource}/{name} List stored instances of a specific class.

Class/type listings are filtered to omit classes disabled by endpoint configuration. The instance-list endpoints query the configured Stateflows storage for context IDs.

For a specific State Machine, Activity, or Action, the standard instance endpoints are:

Method and route Purpose
GET {prefix}/{resource}/{name}/{instance}/status Return behavior status and metadata; ?stream=true streams status updates as server-sent events (SSE).
GET {prefix}/{resource}/{name}/{instance}/notifications Read notifications or stream them; see Status and notifications.
POST {prefix}/{resource}/{name}/{instance}/finalize Send Finalize to the behavior.
DELETE {prefix}/{resource}/{name}/{instance} Send Reset to the behavior.

Actions additionally have POST {prefix}/actions/{name}/{instance}/initialize. A behavior class declared with a default instance also gets default-instance status and notification routes without the {instance} segment, and event routes for that default instance. Default-instance event routes omit Initialize; instance-specific routes are retained as well.

Not every behavior type has every lifecycle route. Entities instead have their own standard routes and data access endpoints, described below.

Event endpoints

The extension discovers event types while visiting registered definitions and maps each mappable accepted event to a POST endpoint:

POST {prefix}/{resource}/{name}/{instance}/{eventName}

For example, a State Machine named Order with an accepted ConfirmOrder event exposes a route of the form:

POST /stateflows/stateMachines/Order/{instance}/confirmOrder

The event segment is the event's short name converted to camel case. An event implementing IRequest<TResponse> is dispatched as a request and its response is included in the HTTP result; other events are sent as one-way events. For a default behavior instance, the route omits {instance}.

The routes come from registered model definitions, not from every CLR type that could be passed directly to SendAsync. State Machine triggers, initialization and custom event registrations, Activity accept-event nodes, Action event registrations, and Entity initializers/mutations contribute event endpoints where applicable. Type mappers can contribute the alternative event types they resolve. The extension does not expose SystemEvents, exceptions, structural events through this CLR-event path, or event types marked [NoApiMapping]. Structural events have their own routes and are described below.

For a non-empty CLR event, the JSON request body has this shape:

{
  "event": {
    "orderId": "A-123"
  },
  "requestedNotifications": ["OrderUpdated"]
}

event is the event payload. For an empty CLR event, omit event; requestedNotifications is optional. Event endpoints accept these query parameters:

Query parameter Default Meaning
implicitInitialization true On instance-addressed routes, allow implicit behavior initialization while handling the event. Set false to suppress it. Default-instance event routes always allow implicit initialization and do not expose this parameter.
stream false Keep the response open as SSE and stream requested notifications while the event is processed.

Event and request responses are JSON envelopes containing the event Status and StatusText; they include EventValidation when invalid, a request Response when present, and optional Notifications, Links, and Metadata. HTTP status codes reflect the Stateflows event status: consumed/duplicated 200, initialized 201, accepted/deferred/forwarded 202, invalid 400, not initialized/rejected/not consumed 409, undelivered 404, overloaded 503, and failed 500. A behavior that cannot be located returns 404.

Notification delivery completion

For CLR and structural event/request endpoints, requestedNotifications (including names added by [NotificationWatch<TNotification>]) establishes a watch before dispatch. After event processing and publication commit, the endpoint waits for the watch callbacks before taking the JSON response's notification snapshot. With stream=true, callbacks write complete SSE frames in order and await each write/flush attempt. A callback merely being scheduled or an observer acknowledging dispatch is not sufficient.

This is best-effort delivery, without retries. Callback/write failures are logged; they do not roll back an already committed event. An SSE flush confirms only the server-side write attempt, not that the remote application received or processed the notification. Disconnecting cancels HTTP waiting and removes its watch. Notifications produced later by independently running streamed Activity work are not part of an ordinary event's completion barrier.

The barrier is outside the publisher transaction, so watch callbacks can send events back to the publisher. Independent watches and durable behavior subscriptions remain asynchronous. Programmatic clients can explicitly call await watcher.WaitForDeliveryAsync() after a send/request; do not await it inside that watch's callback or from behavior processing that its delivery depends on. Custom watcher implementations must implement this barrier for use by these endpoints.

Events carrying [Authorize] metadata are authorized by the mapped endpoint. Configure ASP.NET Core authentication and authorization services in the host, and use event metadata or endpoint conventions to apply the intended access policy.

Activity input and output pins

Each root AddInputPin<TToken> and AddOutputPin<TToken> declaration contributes its own endpoint:

Method and route Purpose
POST {prefix}/activities/{name}/{instance}/input/{tokenType} Inject a typed batch into the Activity's input boundary.
GET {prefix}/activities/{name}/{instance}/output/{tokenType} Wait for the next typed output notification, or stream future output notifications over SSE.

tokenType uses the short event/type name converted to camel case; for example, int maps to int32, string to string, and Order to order. Only the newest registered Activity definition contributes pin routes. Nested/embedded Activity pins are not separate public endpoints. A default instance also gets routes without {instance}.

For example:

.AddActivity("Orders", activity => activity
    .AddInputPin<Order>(pin => pin.AddFlow("Process"))
    .AddAction("Process", async context =>
    {
        var orders = context.GetTokensOfType<Order>();
        foreach (var order in orders)
            context.Output(await ProcessAsync(order));
    }, node => node.AddFlow<OrderResult, OutputPin<OrderResult>>())
    .AddOutputPin<OrderResult>())

The input request is a batch of payloads, not token-holder envelopes:

POST /stateflows/activities/Orders/customer-123/input/order?sendAsStream=true
Content-Type: application/json

{"tokens":[{"orderId":"A-123"},{"orderId":"A-124"}]}
Input query parameter Default Meaning
implicitInitialization true Allow implicit initialization. Set false to reject input to an uninitialized instance. Also available on default-instance pin routes.
sendAsStream false Send TokensInput<TToken> with the Activity Stream header instead of ordinary transactional input.

Ordinary input uses a send, not a token-input request, and returns the standard event-result envelope after processing. Outputs are obtained independently from the output endpoint. With sendAsStream=true, Orleans returns 202 Accepted after volatile admission, without waiting for network completion or issuing a status query behind ongoing transactional work. The response includes the behavior ID; it does not contain output tokens or imply checkpoint durability. Admission errors retain their normal HTTP status. A runtime without Activity streaming support rejects the stream header. See Activity Streaming for execution, checkpoint, and cancellation guarantees.

An output endpoint watches raw TToken notifications published by the root output pin. With stream=false (the default), it waits for the next matching notification and returns 200 with one raw payload:

{"orderId":"A-123","success":true}

With stream=true, it responds with Content-Type: text/event-stream and emits matching notification envelopes:

event: <OrderResult notification name>
data: {"name":"...","payload":{"orderId":"A-123","success":true},"...":"other envelope fields"}

The event value is the framework notification name for the pin's declared type. Each data value is a serialized notification envelope with one raw token at payload. Publication does not synthesize notifications for other CLR types. Neither output mode queries or replays stored notifications. Establish the SSE watch before sending input if its output must be observed; watching does not initialize or execute the Activity, and no output means a one-shot request remains pending until canceled.

Root pins expose retention, TTL, scope, and immediate-dispatch settings in their builder callback. Defaults are live-only: Retain = false, TTL 0. Retained values and positive-TTL history can be retrieved separately through notification requests. See Output Pin and notification retention.

The two options are intentionally different: sendAsStream selects the Activity execution mode on an input POST; stream selects SSE transport on an output GET. SSE can observe ordinary transactional output as well as streamed output.

Disconnecting/canceling an output request disposes its notification watch. This does not cancel Activity execution. SSE uses a bounded 128-notification buffer so HTTP writes do not block the publisher; a consumer that exceeds the buffer is disconnected and the error is logged. There is no durable delivery, reconnect replay, or SSE event-ID cursor on these pin endpoints.

[NoApiMapping] on a token type suppresses its input and output routes. [Authorize] metadata on the token type is evaluated for both directions. Endpoint configuration uses ConfigureEventEndpoint<TokensInput<TToken>> for input and ConfigureEventEndpoint<TToken> for output; standard/default-instance configuration and handler conventions apply normally:

app.MapStateflowsMinimalAPIsEndpoints(api => api
    .ConfigureActivities(activities => activities
        .ConfigureActivity("Orders", activity => activity
            .ConfigureStandardInstances(instances => instances
                .ConfigureEventEndpoint<TokensInput<Order>>(endpoint =>
                    endpoint.ConfigureHandler(handler => handler.RequireAuthorization()))
                .ConfigureEventEndpoint<OrderResult>(endpoint =>
                    endpoint.UpdateRoute(_ => "/orders/{instance}/results"))))));

Two different token types with colliding shortened routes fail endpoint mapping explicitly. Give one a distinct route using its corresponding ConfigureEventEndpoint configuration.

Structural events

Registered structural events have a POST endpoint with the same route pattern and query parameters as CLR events. Their JSON payload is decoded against the registered event definition, and generated OpenAPI metadata describes the structural event fields and supported validation constraints. Structural event names are mapped separately from CLR event types; collisions on the same HTTP method and route are rejected during endpoint mapping.

Structural event definitions must be registered before behavior definitions that accept them. A structural request returns its response according to the request definition. See JSON definitions for registering structural events and payload shape.

Status and notifications

Status endpoints return the behavior's status information, including expected events and behavior-specific state (such as current State Machine states or active Activity nodes). Pass stream=true to receive status update events through SSE. Status queries do not implicitly initialize by default; ?implicitInitialization=true opts into initialization where the route supports that parameter.

Notification endpoints accept repeated names query parameters to select notification types and period to specify how far back to query:

GET {prefix}/stateMachines/Order/{instance}/notifications?names=OrderUpdated&names=AuditWritten&period=00:05:00

Without stream=true, the endpoint returns matching retained notifications from the requested period; the default period is one minute. With stream=true, it streams new notifications using SSE; the default period is zero, so only new notifications are watched. CLR events can declare [NotificationWatch<TNotification>] to include notifications automatically when that event is posted. Event request bodies may also provide requestedNotifications.

Entity endpoints

For each registered Entity, the extension exposes the following routes, subject to the Entity's registered members and endpoint configuration:

Method and route Purpose
GET {prefix}/entities/{name} List stored instances of that Entity class.
GET {prefix}/entities/{name}/{instance}/status Return Entity status and metadata; supports stream=true for status SSE.
GET {prefix}/entities/{name}/{instance}/notifications Read or stream Entity notifications.
DELETE {prefix}/entities/{name}/{instance} Reset the Entity instance.
POST {prefix}/entities/{name}/{instance}/{eventName} Send a registered initializer or mutation event.
GET {prefix}/entities/{name}/{instance}/{projectionName} Request a registered projection. A projection published to the Entity itself also supports stream=true to stream its current value and later updates.
GET {prefix}/entities/{name}/{instance}/{fieldName} Read a field when its access allows FieldAccess.Get.
PUT {prefix}/entities/{name}/{instance}/{fieldName} Set a field when its access allows FieldAccess.Set; the body contains its event value.

Field and projection routes respect the Entity member's field access and [NoApiMapping] attributes. Authorization metadata on Entity mutations and member accessors is applied to the corresponding endpoints. Only the newest registered version of an Entity definition is exposed through this API.

Configure generated endpoints

MapStateflowsMinimalAPIsEndpoints accepts a fluent configuration callback. Configure broadly first, then narrow to a behavior type, class, instance kind, or event. For example:

using Microsoft.AspNetCore.Builder;

app.MapStateflowsMinimalAPIsEndpoints(api => api
    .SetApiRoutePrefix("api/workflows")
    .ConfigureGetAllClassesEndpoint(endpoint =>
        endpoint.ConfigureHandler(handler => handler.RequireAuthorization()))
    .ConfigureStateMachines(stateMachines => stateMachines
        .ConfigureStateMachine<Order>(order => order
            .ConfigureStandardInstances(instances => instances
                .ConfigureEventEndpoint<ConfirmOrder>(endpoint =>
                    endpoint.UpdateRoute(route => route + "/confirm"))))
        .ConfigureEventEndpoint<HealthCheck>(endpoint => endpoint.Disable()))
    .ConfigureEntities(entities => entities
        .ConfigureEntity("Customer", customer => customer
            .ConfigureEventEndpoint("customerRenamed", endpoint =>
                endpoint.ConfigureHandler(handler => handler.RequireAuthorization())))));

The builder scopes are:

Scope Builder methods
All mapped endpoints ConfigureAllEndpoints, ConfigureGetAllClassesEndpoint, ConfigureGetAllInstancesEndpoint, ConfigureAllCustomEndpoints
A behavior type ConfigureStateMachines, ConfigureActivities, ConfigureActions, ConfigureEntities; within each, configure all endpoints, class listings, instance listings, or custom endpoints for that type
One behavior class ConfigureStateMachine, ConfigureActivity, ConfigureAction, or ConfigureEntity, selected by class name, class descriptor, or (where supported) behavior type
One class's instance family ConfigureDefaultInstance and ConfigureStandardInstances distinguish the default instance from instances addressed by an {instance} route segment
One event endpoint ConfigureEventEndpoint<TEvent> selects a CLR event; ConfigureEventEndpoint("eventName", ...) selects an event by registered name. The name form also applies to CLR events whose Stateflows event name matches. ConfigureAllEventEndpoints and ConfigureEventEndpoints<T1, ...> apply the same rule to groups of event endpoints.

Each scope provides IEndpointConfiguration:

  • Disable() suppresses matching generated endpoints.
  • UpdateRoute(route => ...) transforms each matching route. The method is unchanged by this operation.
  • ConfigureHandler(handler => ...) applies ASP.NET Core endpoint conventions after the endpoint is mapped, for example RequireAuthorization(), tags, metadata, or filters.

Multiple configuration calls are additive. Narrower configuration scopes match only their target type/class/event/instance family, while broad rules continue to apply. The endpoint configuration API does not change HTTP methods; implement IEndpointDefinitionInterceptor and register it with AddEndpointDefinitionInterceptor<TInterceptor>() when route methods must be changed or endpoint definition needs custom logic. Interceptors can update route/method before mapping, suppress endpoint registration, and apply conventions after mapping.

MapValidationSchema<TAttribute> registers a mapping from a validation attribute to OpenAPI schema constraints for structural event endpoints created by that mapping call. Built-in DataAnnotations mappings are provided when the attribute's semantics can be represented exactly.

Add custom endpoints

Use AddEndpoints in a State Machine, state, Activity, structured Activity, or Action definition. The generated route is under the behavior class and instance; when the class has a default instance, a default-instance route is generated too. State- and node-scoped endpoints are filtered to be available only while their containing state or node is active.

For a custom pattern /summary, the usual instance route is /{resource}/{name}/{instance}/summary; the default-instance route is /{resource}/{name}/summary.

using Microsoft.AspNetCore.Http;
using Stateflows.Extensions.MinimalAPIs;
using Stateflows.Extensions.MinimalAPIs.Interfaces;
using Stateflows.StateMachines;

public sealed class Order : IStateMachine
{
    public static void Build(IStateMachineBuilder machine) => machine
        .AddInitialState("Ready", state => state
            .AddEndpoints(endpoints =>
                endpoints.AddGet("/where", (IStateEndpointContext context) =>
                    Results.Ok(new { State = context.State.Name })))
            .AddTransition<ConfirmOrder>("Confirmed"))
        .AddFinalState("Confirmed");
}

IEndpointsBuilder supports AddGet, AddPost, AddPatch, AddPut, AddDelete, and AddMethods. A handler can use the relevant endpoint context and ordinary Minimal API dependencies. Apply host authorization or other ASP.NET Core conventions to the returned route group or configure matching custom endpoints through the mapping callback.

Shared package and security

Stateflows.Extensions.MinimalAPIs.Common supplies shared attributes such as [NoApiMapping] and [NotificationWatch<TNotification>]; the main Minimal APIs package references it. Use [NoApiMapping] to omit eligible mapped events, Entity members, projections, or custom API declarations.

The extension maps behavior operations and data access routes, so treat the API as an application boundary: configure authentication, authorization, route exposure, and tenant handling deliberately. Event authorization metadata and Entity member authorization are honored by generated routes; use ConfigureHandler(...RequireAuthorization()) or endpoint interceptors for broader policies. See the extension source for the endpoint contracts and implementation details.

Clone this wiki locally