CareflowDocumentation

Using the .NET SDK

Last Updated: October 15, 2026


This guide walks you through creating a .NET application using the Careflow SDK, packaging it as a Docker image, and preparing it for deployment as an embedded application on the Careflow platform.

It covers:

  • Project setup
  • SDK integration
  • Configuration
  • Usage
  • Dockerization
  • Deployment

The end result is a working Docker image ready for Careflow deployment.

1. Prerequisites

Before you start, ensure you have:

  • .NET 8 SDK (or newer)
  • Docker

You will also need the following for local development testing:

  • Careflow Azure DevOps PAT
  • Application Client ID
  • Application Client Secret
  • Connector Secret
  • App Server base URL
  • Connector base URL
  • WS Gateway base URL

These environment variables will be automatically set once the application is deployed on Careflow, and will not need to be manually set.

The PAT and secret will be provided on request, as an application needs to be initially created to generate them. Secrets are not publicly exposed and require a system admin to provide if needed for local development testing.

2. Create the Project

Open a terminal and run:

bash
mkdir my-careflow-app
cd my-careflow-app
 
dotnet new sln -n my-careflow-app
dotnet new mvc -n MyCareflowApp -o src/MyCareflowApp
dotnet sln add src/MyCareflowApp/MyCareflowApp.csproj

Your project structure should look like:

plaintext
my-careflow-app/
├── my-careflow-app.sln
└── src/
   └── MyCareflowApp/
 

3. Configure NuGet Feed

Create a file named NuGet.Config at the root:

xml
<configuration>
 <packageSources>
   <clear />
   <add key="Careflow"
        value="https://pkgs.dev.azure.com/careflowhealth/Careflow/_packaging/Careflow/nuget/v3/index.json" />
   <add key="nuget.org"
        value="https://api.nuget.org/v3/index.json" />
 </packageSources>
 <packageSourceCredentials>
   <Careflow>
     <add key="Username" value="AzureDevOps" />
     <add key="ClearTextPassword" value="%NUGET_CAREFLOW_PAT%" />
   </Careflow>
 </packageSourceCredentials>
</configuration>

Set your PAT locally (this is currently provisioned on a request basis):

bash
export NUGET_CAREFLOW_PAT="your-pat"

4. Install the SDK

bash
cd src/MyCareflowApp
dotnet add package Careflow.Sdk

5. Register the Client

Open Program.cs and create a singleton client:

csharp
builder.Services.AddSingleton<ICareflowClient>(_ =>
{
   var options = new ClientOptions
   {
       AppBaseUrl       = new Uri("https://qa-controller.careflow.ca"),
       ConnectorBaseUrl = new Uri("https://qa-connector.careflow.ca"),
       WsGatewayBaseUrl = new Uri("https://qa-wsgateway.careflow.ca"),
       Timeout          = TimeSpan.FromSeconds(30),
       MaxRetryCount    = 3,
       VerifySsl        = true,
   };
 
   return new CareflowClient(options);
});

6. Configure X-Forwarded-Prefix

When the app is hosted behind the Careflow proxy, requests may include an X-Forwarded-Prefix header. Use it to set PathBase so MVC routes, static files, and generated links resolve correctly when the app is mounted under a subpath instead of /.

Add this middleware after var app = builder.Build():

csharp
app.Use((context, next) =>
{
    if (context.Request.Headers.TryGetValue("X-Forwarded-Prefix", out var values))
    {
        var prefix = values.ToString();
        if (!string.IsNullOrWhiteSpace(prefix))
        {
            if (!prefix.StartsWith('/')) prefix = "/" + prefix;
            context.Request.PathBase = new PathString(prefix.TrimEnd('/'));
        }
    }
 
    return next();
});

7. Configure Environment Variables

For local development, the SDK reads its configuration from ClientOptions — either the values you assign directly (as in Section 5) or the CAREFLOW_SDK_* environment variables listed below. The SDK does not read appsettings.json on its own.

If you prefer to keep configuration in appsettings.json, add a section like the following and bind it yourself when constructing the client (e.g. builder.Configuration.GetSection("Careflow")):

json
{
 "Careflow": {
   "AppBaseUrl": "...",
   "ConnectorBaseUrl": "...",
   "WsGatewayBaseUrl": "...",
   "Timeout": 30,
   "MaxRetryCount": 3,
   "VerifySsl": true
 }
}

Available expected environment variables

CAREFLOW_SDK_CONTROLLER_BASE_URL

CAREFLOW_SDK_CONNECTOR_BASE_URL

CAREFLOW_SDK_WS_GATEWAY_BASE_URL

CAREFLOW_SDK_CLIENT_ID

CAREFLOW_SDK_CLIENT_SECRET

CAREFLOW_SDK_CONNECTOR_SECRET (required for publish, subscribe and streaming)

(Optional)

CAREFLOW_SDK_CLIENT_CERT_PATH

CAREFLOW_SDK_CLIENT_KEY_PATH

CAREFLOW_SDK_CA_BUNDLE_PATH

Note: These environment variables are already injected by Careflow by default, app developers using the SDK do not need to specify these in their uploaded .env configuration files.

8. Authentication (HMAC)

Each request includes:

x-app-uuid

x-timestamp

x-signature

Signature format:

METHOD

PATH

TIMESTAMP

SHA256(body)

No Bearer tokens required. Fully handled by the SDK.

9. Using the App API (client.App)

Get Deployment

csharp
Task<CareflowResponse<DeploymentData>> GetDeploymentAsync(
    GetDeploymentParams parameters,
    CancellationToken cancellationToken = default
)

Retrieve deployment metadata. This is an essential API providing all necessary deployment details used for interacting with topics, and other parts of the App deployment.

Maps to: GET /api/v1/deployment

Example:

csharp
var response = await client.App.GetDeploymentAsync(
    new GetDeploymentParams
    {
    }
);

Example response payload:

json
{
  "status": "ok",
  "data": {
    "deployment_yaml": {
      "models": [
        {
          "name": "app-name-123",
          "model": "sample-app",
          "artifacts": [
            {
              "tag": "organization/app-image-name:latest",
              "label": "test",
              "topics": {
                "in": [
                  { "topic": "patient-input" }
                ],
                "out": "results-output"
              },
              "artifact_id": 47,
              "configuration": { ... },
              "instance_type": "t3.small",
              "root_disk_size": "50Gi",
              "deployment_instance_id": "33",
              "deployment_instance_uuid": "c6bf477b-a701-4171-834c-7fc1033deb43"
            }
          ],
          "version": "1.0.0",
          "model_id": 12,
          "version_id": 37,
          "deployment_model_id": "33"
        }
      ],
      "topics": [
        {
          "name": "patient-input",
          "type": "JSON",
          "topic": "patient-input",
          "display": "Patient Input",
          "dataset_id": 26
        },
        {
          "name": "results-output",
          "type": "JSON",
          "topic": "my-project_results-output_3dba02ccc9760ba0",
          "display": "Results Output",
          "dataset_id": 28
        }
      ],
      "project": {
        "name": "my-project",
        "key_name": "my-project",
        "description": "My project description",
        "deploy_cluster": false,
        "stakeholder_id": 1
      },
      "deployment_package_id": 23
    }
  }
}

Understanding topic references:

The topics.in and topics.out values inside each image entry are reference names, not the actual topic identifiers. To obtain the real topic string to use when publishing or subscribing, look up the reference name in the top-level topics array by matching the name field.

For example, the image above declares:

json
"topics": {
  "in":  [{ "topic": "patient-input" }],
  "out": "results-output"
}

These reference names resolve to the following entries in deploymentYaml.topics:

Reference nameResolved topic value
patient-inputpatient-input
results-outputmy-project_results-output_3dba02ccc9760ba0

Use the resolved topic value (not the reference name) when publishing or subscribing:

csharp
// 1. Fetch the deployment once and cache it.
var deployment = await client.App.GetDeploymentAsync(new GetDeploymentParams());
var topics = deployment.Data.DeploymentYaml.Topics;
 
// 2. Find the resolved topic by its reference name.
var outTopic = topics.First(t => t.Name == "results-output").Topic;
// outTopic == "my-project_results-output_3dba02ccc9760ba0"
 
// 3. Use the resolved topic when publishing.
await client.Connector.PublishAsync(new ConnectorPublishParams
{
    Topic = outTopic,
    Payload = new { /* ... */ },
});

Deprecated: client.App.PublishAsync, SubscribeAsync and FlushAsync will be removed in a future major version. Use the Connector API instead (see Using the Connector API).

Notes:

  • App requests are signed by default; set RequireSigning = false only to send one unsigned.
  • HMAC signing is handled automatically.

Streaming (Real-Time)

ConnectAsync opens a persistent WebSocket connection to the WsGateway and yields messages as they arrive across one or more topics. Unlike client.Connector.SubscribeAsync (which polls), streaming is push-based and stays open until the cancellation token is cancelled.

Setup

Streaming requires CAREFLOW_SDK_WS_GATEWAY_BASE_URL and CAREFLOW_SDK_CONNECTOR_SECRET to be set.

Use the resolved topic values from GetDeploymentAsync (same as publishing):

csharp
var deployment = await client.App.GetDeploymentAsync(new GetDeploymentParams());
var outTopic = deployment.Data.DeploymentYaml.Topics.First(t => t.Name == "results-output").Topic;
await foreach (var message in client.Streaming.ConnectAsync(new ConnectParams
{
	Topics = [outTopic]
}))
{
	Console.WriteLine($"[{message.Topic}] {message.Value}");
}  

Multi-Topic

Multiple topics can be subscribed to in a single connection:

csharp
await foreach (var message in client.Streaming.ConnectAsync(new ConnectParams
{
	Topics = [inputTopic, outputTopic]
}))
{
	// message.Topic tells you which topic this message came from
}

Notes:

  • The gateway allows only one active connection per ConnectorSecret.
  • Reconnect on disconnect is automatic with exponential backoff (configurable via ConnectOptions). Transient errors are reported via ConnectOptions.OnError and retried; only authentication rejection, invalid topics, cancellation, and reconnect exhaustion end the stream.
  • Each reconnect resumes from the latest Kafka offset, not from the beginning.
  • Set SeekToLatest = true on ConnectParams to skip the backlog and only receive data published after connecting.
  • Idle connections are kept alive automatically (ConnectOptions.KeepAliveInterval, default 15 seconds) so dead connections are detected and reconnected.
  • For serving multiple concurrent clients (e.g. SSE endpoints), use a single ConnectAsync connection with a broadcaster pattern rather than opening one connection per client.

Possible Exceptions:

  • WsAuthenticationException - authentication rejected by the WsGateway
  • WsInvalidTopicException - one or more requested topics are not provisioned
  • WsReconnectExhaustedException - max reconnect attempts exceeded

10. Using the Connector API (client.Connector)

The connector parameter types live under Careflow.Sdk.Models.Connectors and share their names (PublishParams, SubscribeParams) with the App models. Alias them to avoid ambiguity:

csharp
using ConnectorPublishParams = Careflow.Sdk.Models.Connectors.PublishParams;
using ConnectorSubscribeParams = Careflow.Sdk.Models.Connectors.SubscribeParams;

Publish

csharp
await client.Connector.PublishAsync(new ConnectorPublishParams
{
   Topic = request.Topic,
   Payload = request.Payload
});

Subscribe

csharp
await client.Connector.SubscribeAsync(new ConnectorSubscribeParams
{
   Topic = topic
});

11. Using the Pipeline API (client.Pipeline)

The Pipeline API dispatches named commands to the broker. The command is named in the request body rather than by route, so commands the broker adds later work without an SDK release.

csharp
using Careflow.Sdk.Models.Pipeline;
 
var deployment = await client.Pipeline.ExecuteAsync(new ExecuteParams
{
   Command = PipelineCommands.DeploymentGet,
});
 
var models = deployment.Data!["result"]
    .GetProperty("deployment_pipelines")
    .GetProperty("models");

PipelineCommands lists the commands known today (DeploymentGet, DeploymentList, DeploymentStatus, ArtifactGet, RunStart, RunStatus, RunStop) for autocomplete only — Command accepts any non-empty string. DeploymentGet takes no parameters; the others take the deployment_instance_uuid it returns. See .NET SDK for each command's parameters and a full run example.

12. Test Locally

bash
export CAREFLOW_SDK_CLIENT_ID="..."
export CAREFLOW_SDK_CLIENT_SECRET="..."
export CAREFLOW_SDK_CONNECTOR_SECRET="..."
dotnet run

Create some test endpoints:

bash
curl http://localhost/healthz
curl http://localhost/api/app/deployment

13. Dockerfile

Create a file named Dockerfile, update the corresponding fields for your application:

dockerfile
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG NUGET_CAREFLOW_PAT
WORKDIR /src
COPY NuGet.Config .
COPY src/MyCareflowApp/ ./MyCareflowApp/
WORKDIR /src/MyCareflowApp
RUN dotnet restore
RUN dotnet publish -c Release -o /app/publish
 
LABEL org.label-schema.name="careflow-sdk-net-sample"
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app/publish .
ENV ASPNETCORE_URLS=http://+:80
EXPOSE 80
ENTRYPOINT ["dotnet", "MyCareflowApp.dll"]

14. Build and Run

Build:

bash
docker build \
 --build-arg NUGET_CAREFLOW_PAT="$NUGET_CAREFLOW_PAT" \
 -t my-careflow-app:local .

Run:

bash
docker run -p 80:80 \
 -e CAREFLOW_SDK_CLIENT_ID="..." \
 -e CAREFLOW_SDK_CLIENT_SECRET="..." \
 -e CAREFLOW_SDK_CONNECTOR_SECRET="..." \
 my-careflow-app:local

15. Push to Registry

bash
docker tag my-careflow-app:local user/my-careflow-app:1.0.0
docker push user/my-careflow-app:1.0.0

16. Deployment

Have the following on hand when preparing to deploy the embedded application to Careflow:

  • Image name and tag for your embedded application image
  • Required environment variables in a .env file (if your application has any that are not automatically provided)
  • Input / Output / Control topics

Checklist

  • No secrets committed
  • PAT not included in the image being deployed
  • Singleton client configured
  • /healthz endpoint works
  • Signed App requests
  • Proper error handling
  • Immutable image tags