Getting started

This page takes you from an empty project to a completed human task over HTTP. You add the engine with its PostgreSQL store, write an order approval workflow, host it in ASP.NET Core, start an instance and complete its task with an access token. Every file and command you need is on this page.

Prerequisites

1. Create the projects

Create an empty folder for the solution and put this nuget.config in it. It takes the Workflow packages from the Stella Ops feed and every other package from nuget.org:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!-- The Workflow packages come from the Stella Ops feed, every other package from nuget.org.
       Package source mapping keeps StellaOps.* off nuget.org. -->
  <packageSources>
    <clear />
    <add key="stella-ops" value="https://nuget.stella-ops.org/v3/index.json" />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
  <packageSourceMapping>
    <packageSource key="stella-ops">
      <package pattern="StellaOps.*" />
    </packageSource>
    <packageSource key="nuget.org">
      <package pattern="*" />
    </packageSource>
  </packageSourceMapping>
</configuration>

Keep the workflows in a library of their own. The library references only the authoring package, which also brings the analyzer that checks the workflow code at compile time. Set WORKFLOW_VERSION to the version of a Workflow release that https://nuget.stella-ops.org lists; the value below shows the form only:

WORKFLOW_VERSION=1.0.0-20261110T090000Z

dotnet new classlib -n Contoso.Approvals.Workflows
dotnet new web -n Contoso.Approvals.Host
dotnet add Contoso.Approvals.Host reference Contoso.Approvals.Workflows

dotnet add Contoso.Approvals.Workflows package StellaOps.Workflow.Abstractions --version "$WORKFLOW_VERSION"
dotnet add Contoso.Approvals.Host package StellaOps.Workflow --version "$WORKFLOW_VERSION"
dotnet add Contoso.Approvals.Host package StellaOps.Workflow.AspNetCore --version "$WORKFLOW_VERSION"
dotnet add Contoso.Approvals.Host package StellaOps.Workflow.Transport.Http --version "$WORKFLOW_VERSION"
dotnet add Contoso.Approvals.Host package Microsoft.AspNetCore.Authentication.JwtBearer --version 10.0.0

StellaOps.Workflow installs the engine and the PostgreSQL store. Every Workflow package gets the same version (Packages). The JWT bearer package is pinned to version 10.0.0 so that a later major version does not target another .NET version. For central package management, a lock file and a signature check, read Add Workflow to your project.

2. Write the workflow

The order approval workflow opens one review task. An approved order is sent to a fulfilment service with an endpoint call; a rejected order ends the workflow. Put both classes in the workflows library; the file needs using StellaOps.Workflow.Abstractions; and using StellaOps.Workflow.Contracts;.

/// <summary>The start request of the order approval workflow.</summary>
public sealed class OrderApprovalRequest
{
    /// <summary>The business key: instances and tasks can be searched by it.</summary>
    [WorkflowBusinessId]
    public string OrderId { get; set; } = string.Empty;

    public string Customer { get; set; } = string.Empty;

    public decimal Amount { get; set; }
}
/// <summary>
/// One human review of an order. An approved order is sent to the fulfilment service;
/// a rejected order ends the workflow.
/// </summary>
public sealed class OrderApprovalWorkflow : IDeclarativeWorkflow<OrderApprovalRequest>
{
    public string WorkflowName => "OrderApproval";

    public string WorkflowVersion => "1.0.0";

    public string DisplayName => "Order approval";

    public IReadOnlyCollection<string> WorkflowRoles { get; } = ["order-approver"];

    public WorkflowSpec<OrderApprovalRequest> Spec { get; } = WorkflowSpec.For<OrderApprovalRequest>()
        .InitializeState(
            WorkflowExpr.Obj(
                WorkflowExpr.Prop("orderId", WorkflowExpr.Path("start.orderId")),
                WorkflowExpr.Prop("customer", WorkflowExpr.Path("start.customer")),
                WorkflowExpr.Prop("amount", WorkflowExpr.Path("start.amount")),
                WorkflowExpr.Prop("decision", WorkflowExpr.Null())))
        .AddTask(
            WorkflowHumanTask.For<OrderApprovalRequest>("Review order", "OrderReview", "orders/review")
                .WithPayload(
                    WorkflowExpr.Obj(
                        WorkflowExpr.Prop("orderId", WorkflowExpr.Path("state.orderId")),
                        WorkflowExpr.Prop("customer", WorkflowExpr.Path("state.customer")),
                        WorkflowExpr.Prop("amount", WorkflowExpr.Path("state.amount"))))
                .OnComplete(flow => flow
                    .Set("decision", WorkflowExpr.Path("payload.decision"))
                    .WhenExpression(
                        "Approved?",
                        WorkflowExpr.Eq(WorkflowExpr.Path("payload.decision"), WorkflowExpr.String("approve")),
                        approved => approved
                            .Call(
                                "Send to fulfilment",
                                new EndpointAddress("fulfilment", "/fulfilment/orders"),
                                WorkflowExpr.Obj(
                                    WorkflowExpr.Prop("orderId", WorkflowExpr.Path("state.orderId")),
                                    WorkflowExpr.Prop("amount", WorkflowExpr.Path("state.amount"))),
                                whenFailure: failed => failed
                                    .Set("fulfilment", WorkflowExpr.String("failed"))
                                    .Complete(),
                                whenTimeout: timedOut => timedOut
                                    .Set("fulfilment", WorkflowExpr.String("timed-out"))
                                    .Complete())
                            .Set("fulfilment", WorkflowExpr.String("sent"))
                            .Complete(),
                        rejected => rejected.Complete())))
        .StartWith(flow => flow.ActivateTask("Review order"))
        .Build();

    public IReadOnlyCollection<WorkflowTaskDescriptor> Tasks => Spec.TaskDescriptors;
}

Every value is an expression (WorkflowExpr), not C# code: the engine can store, validate and render the definition, and the analyzer reports C# that it could not express (Defining workflows).

Register the workflow with its start request type, so the start payload binds to OrderApprovalRequest and OrderId becomes the business key. Add this class to the workflows library; the file needs using Microsoft.Extensions.DependencyInjection; and using StellaOps.Workflow.Abstractions;:

public static class OrderApprovalRegistrations
{
    /// <summary>
    /// Registers the order approval workflow with its start request type, so that a start payload is
    /// bound to <c>OrderApprovalRequest</c> and its <c>[WorkflowBusinessId]</c> property becomes the
    /// business key.
    /// </summary>
    public static IServiceCollection AddOrderApprovalWorkflow(this IServiceCollection services)
        => services.AddWorkflowRegistration<OrderApprovalWorkflow, OrderApprovalRequest>();
}

3. Compose the host

Replace the Program.cs of the host with the following parts, in this order. The file needs these using directives: Microsoft.AspNetCore.Authentication.JwtBearer, Microsoft.AspNetCore.Diagnostics.HealthChecks, StellaOps.Workflow.AspNetCore, StellaOps.Workflow.DataStore.PostgreSQL, StellaOps.Workflow.Engine.Services, StellaOps.Workflow.Transport.Http, the namespace of your registration class and, if you add the stand-in below, its namespace Examples.Workflow.Host.StandIn.

Start with var builder = WebApplication.CreateBuilder(args);, then register the engine and its store:

// The engine and its PostgreSQL store. The store reads its connection string from
// STELLAOPS_POSTGRES_WORKFLOW_CONNECTION and creates the `workflow` schema at start.
builder.Services.AddWorkflowEngineCoreServices(builder.Configuration);
builder.Services.AddWorkflowPostgresDataStore(builder.Configuration);

// The signal pump, the retention job and the licence monitor, with its `licence` health entry.
builder.Services.AddWorkflowEngineHostedServices();

// Fails at start when WorkflowBackend:Provider or WorkflowSignalDriver:Provider names a backend
// or a signal driver that no registered library provides.
builder.Services.ValidateWorkflowProviderRegistrations(builder.Configuration);

The workflow calls the fulfilment service with an endpoint call, which needs the HTTP transport. Without it the host stops at start with WFIMP010 ... 'transport.endpoint' is not installed:

// `endpoint` and `http` calls (WorkflowEndpointTransport:Services, WorkflowHttpTransport:Targets).
builder.Services.AddWorkflowHttpTransport(builder.Configuration);

The workflow:

builder.Services.AddOrderApprovalWorkflow();

Authentication and the Workflow policies:

// JWT bearer tokens (Authentication:Schemes:Bearer). The workflow scopes travel in the `scope`
// claim; MapInboundClaims = false keeps the claim names of the token.
builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => options.MapInboundClaims = false);

// The three Workflow policies, and the actor of a task action taken from the token: the actor ID from
// `sub` and the roles from the `role` claims (WorkflowAuthorization:ActorIdClaimTypes, RoleClaimTypes).
builder.Services.AddWorkflowAuthorization();

AddWorkflowAuthorization also makes task actions act as the caller: the actor ID comes from the token’s sub claim and the roles from its role claims (Hosting).

If you have no fulfilment service yet, add a stand-in for it to the host project: the file StandIn/StandInServices.cs below answers the fulfilment call on the host itself and records it (it also answers a payments call, which this page does not use).

using System.Collections.Concurrent;
using System.Net;
using System.Text.Json;

namespace Examples.Workflow.Host.StandIn;

/// <summary>The calls the stand-in services received, in arrival order.</summary>
public sealed class StandInCallLog
{
    private readonly ConcurrentQueue<StandInCall> calls = new();

    public void Add(StandInCall call) => calls.Enqueue(call);

    public IReadOnlyCollection<StandInCall> All() => calls.ToArray();
}

public sealed record StandInCall(string Service, string Path, JsonElement Body);

/// <summary>
/// Stand-ins for the fulfilment and payments services that the example workflows call. They answer
/// loopback callers only, record each call and return 200. A real deployment points
/// WorkflowEndpointTransport:Services:fulfilment and WorkflowHttpTransport:Targets:payments at the real
/// services instead.
/// </summary>
public static class StandInServices
{
    public static IEndpointRouteBuilder MapStandInServices(this IEndpointRouteBuilder app)
    {
        app.MapPost("/stand-in/fulfilment/orders", (HttpContext context, JsonElement body, StandInCallLog log) =>
            Record(context, log, "fulfilment", body)).AllowAnonymous();
        app.MapPost("/stand-in/payments/claims", (HttpContext context, JsonElement body, StandInCallLog log) =>
            Record(context, log, "payments", body)).AllowAnonymous();
        app.MapGet("/stand-in/calls", (HttpContext context, StandInCallLog log) =>
            IPAddress.IsLoopback(context.Connection.RemoteIpAddress ?? IPAddress.None)
                ? Results.Ok(log.All())
                : Results.StatusCode(StatusCodes.Status403Forbidden)).AllowAnonymous();
        return app;
    }

    private static IResult Record(HttpContext context, StandInCallLog log, string service, JsonElement body)
    {
        if (!IPAddress.IsLoopback(context.Connection.RemoteIpAddress ?? IPAddress.None))
        {
            return Results.StatusCode(StatusCodes.Status403Forbidden);
        }

        log.Add(new StandInCall(service, context.Request.Path, body.Clone()));
        return Results.Ok(new { accepted = true });
    }
}

Register its call log:

// Stand-ins for the services that the example workflows call (StandIn/StandInServices.cs).
builder.Services.AddSingleton<StandInCallLog>();

Build the application and add authentication to its pipeline:

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

Map the health endpoints, which step 6 uses, and the Workflow endpoints:

// Liveness: the process answers. Readiness: every health check, written with the Workflow
// response writer, which shows the informational `licence` entry with its data.
app.MapHealthChecks("/healthz", new HealthCheckOptions { Predicate = _ => false }).AllowAnonymous();
app.MapHealthChecks("/readyz", new HealthCheckOptions { ResponseWriter = WorkflowHealthResponseWriter.WriteAsync })
    .AllowAnonymous();
// Every Workflow endpoint under /api/workflow, each behind one of the View, Operate and Admin policies.
app.MapWorkflowEndpoints();

Map the stand-in fulfilment service, if you copied it, and end with app.Run();:

app.MapStandInServices();

4. Configure

appsettings.json selects the store, the signal driver and the runtime provider, and names the fulfilment service:

{
  "WorkflowBackend": { "Provider": "Postgres" },
  "WorkflowSignalDriver": { "Provider": "Native" },
  "WorkflowRuntime": { "DefaultProvider": "Stella.Engine" },
  "WorkflowEndpointTransport": {
    "Services": {
      "fulfilment": { "Url": "<base URL of the fulfilment service>" }
    }
  }
}

With the stand-in of step 3, the fulfilment service is the host itself: set the URL to the host’s address of step 6 followed by stand-in/. With a real fulfilment service, put its base URL here. WorkflowRuntime:DefaultProvider names the canonical engine, the default, which runs exactly the definition that it validates, stores and renders (Hosting).

The connection string comes from STELLAOPS_POSTGRES_WORKFLOW_CONNECTION and nowhere else. Keep it out of appsettings.json: in development, use the user secrets store; in production, an environment variable or your secret store.

cd Contoso.Approvals.Host
dotnet user-secrets init
dotnet user-secrets set STELLAOPS_POSTGRES_WORKFLOW_CONNECTION "Host=localhost;Port=5432;Database=workflow;Username=workflow;Password=<password>"

Expected result: at the first start the store creates the workflow schema in that database. The role needs the right to create a schema in the database (Persistence and signals).

5. Get a token

The endpoints accept JWT bearer tokens with the workflow scopes in the scope claim. For a local run, dotnet user-jwts creates a signing key in the user secrets, writes the issuer and the audience into appsettings.Development.json (Authentication:Schemes:Bearer), and prints a token whose sub is the name, with scope and role claims:

dotnet user-jwts create --audience workflow-host --name approver-1 \
  --scope "workflow:view" --scope "workflow:operate" --role order-approver
ScopeAllows
workflow:viewReading definitions, instances, tasks, diagrams
workflow:operateStarting workflows, task actions, raising signals (and everything workflow:view allows)
workflow:adminImporting and activating definitions, retention, dead-letter replay (and everything above)

The role claim is the actor’s role. The review task can be completed only by a caller whose roles include one of the task’s roles, here the workflow role order-approver.

6. Run

From the host folder (the folder of step 4):

dotnet run --urls http://localhost:5090

Expected result: the log shows the schema migration and the line Workflow licence status within-free-limit: Recorded workflow-name count: 1. GET http://localhost:5090/readyz answers 200.

7. Start an instance

TOKEN=<the token printed by dotnet user-jwts>
START=$(curl -s -X POST http://localhost:5090/api/workflow/start \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"workflowName":"OrderApproval","payload":{"orderId":"ORD-1001","customer":"Northwind Traders","amount":250.0}}')
echo "$START"
INSTANCE_ID=$(echo "$START" | jq -r .workflowInstanceId)
TASK_ID=$(echo "$START" | jq -r '.nextTasks[0].workflowTaskId')

Expected result (abridged):

{
  "workflowInstanceId": "<instance id>",
  "workflowName": "OrderApproval",
  "workflowVersion": "1.0.0",
  "businessReference": { "key": "ORD-1001", "parts": { "OrderId": "ORD-1001" } },
  "nextTasks": [ { "workflowTaskId": "<task id>", "taskName": "Review order", "status": "Open" } ],
  "workflowState": { "orderId": "ORD-1001", "customer": "Northwind Traders", "amount": 250.0, "decision": null }
}

8. Complete the task

INSTANCE_ID and TASK_ID come from the start response of step 7. List the open tasks of the instance, then complete the review with the decision in the payload:

curl -s "http://localhost:5090/api/workflow/tasks?workflowInstanceId=$INSTANCE_ID&status=Open" \
  -H "Authorization: Bearer $TOKEN"

curl -s -X POST http://localhost:5090/api/workflow/tasks/$TASK_ID/complete \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"payload":{"decision":"approve"}}'

Expected result: "completed": true, no next task. The engine calls the fulfilment service, and the instance is Completed:

curl -s http://localhost:5090/api/workflow/instances/$INSTANCE_ID -H "Authorization: Bearer $TOKEN"

The workflowState of the instance shows "decision": "approve" and "fulfilment": "sent".

What can go wrong

SymptomCauseAction
The host stops at start with WFIMP010 ... 'transport.endpoint' is not installedThe HTTP transport is not registeredAdd AddWorkflowHttpTransport (step 3)
The host stops at start: “The PostgreSQL workflow backend requires a connection string”STELLAOPS_POSTGRES_WORKFLOW_CONNECTION is not set in the environment the host runs inSet it (step 4)
401 on every requestThe token is missing, expired, or signed for another audienceCreate a token for the audience workflow-host
403 on startThe token lacks workflow:operateAdd the scope
The task completion answers 403 with WorkflowTaskActionDeniedThe caller’s roles do not include a role of the taskGive the caller the order-approver role
The instance completes with "fulfilment": "failed"The fulfilment service is not reachable at the configured URLCheck WorkflowEndpointTransport:Services:fulfilment:Url

More in Troubleshooting.

Next