Skip to content

Extension Minimal APIs

Mikołaj Milewski edited this page Oct 27, 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, 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, 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.

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.

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.

Overview
Installation
Runtimes
   Orleans runtime
Concepts
   Events and Structural Events
   Messaging Patterns
   Validation
   Scheduling
   Observability
Behaviors
   Behavior Values
   Dependency Injection
   Behavioral Groups
   State Machines
       Concepts
           State Identity
           In-State Event Deferrals
           Evaluation of Transitions
           Exception Handling
       Building blocks
           Regions
           States
               State
               Composite State
               Orthogonal State
               Final State
           Pseudostates
               Choice
               Junction
               Fork
               Join
               History
           Transitions
               Transition
               Default Transition
               Internal Transition
   Activities
       Concepts
           Exception Handling
           Implicit Fork and Join
           Tokens
       Building blocks
           Nodes
               Action Node
               Decision Node
               Merge Node
               Initial Node
               Final Node
               Input Node
               Output Node
               Fork Node
               Join Node
               Accept Event Action Node
               Send Event Action Node
               Publish Event Action Node
               Time Event Action Node
               Data Store Node
               Structured Activity Node
               Iterative Activity Node
               Parallel Activity Node
           Flows
               Data Flow
               Control Flow
   Actions
   Entities
       Fields
       Mutations
       Projections
Extensions
   ClearScript
   FluentValidation
   JSON definitions
   Minimal APIs
   OneOf
   OpenTelemetry
   PlantUML
   Scheduling

Clone this wiki locally