Skip to content
FlagSwiftDocs

.NET SDK

ASP.NET Core dependency injection and a route attribute.

Use this SDK in ASP.NET Core applications, worker services and any .NET 8 program. It downloads your environment's configuration, keeps it fresh with background polling and evaluates every flag in memory, so a check never touches the network. For other backends see the Java and Go SDKs. Options and behaviour every SDK shares are on Options and behaviour.

Not yet compiled

The .NET SDK has not been compiled or run. Run dotnet test first and expect to fix a compile error or two. The package ids are also placeholders until the publishing location is decided.

At a glance#

Install
dotnet add package FlagSwift
Requires
.NET 8+
Key
Server key (fs_srv_)
Evaluates
Locally, in memory
Real-time updates
No, it polls
Works offline from
Snapshot file
Outcome analytics
Yes
Verified
Not yet compiled

Options, user context and behaviour every SDK shares are on Options and behaviour. To compare SDKs, see SDK features.

Installation#

bash
dotnet add package FlagSwift
dotnet add package FlagSwift.Extensions.DependencyInjection

It needs .NET 8 or newer. The core FlagSwift package has no dependencies. FlagSwift.Extensions.DependencyInjection adds the registration helper and the MVC attribute, and is optional without ASP.NET.

Initialization#

You need a server key (fs_srv_…) or admin key with the evaluation:read scope, and the address of your FlagSwift server. Keep both in configuration, never in source control. Register the client once as a singleton. A hosted service loads the configuration at startup, and a failed or slow first fetch does not stop the app.

Program.cs
builder.Services.AddFlagSwift(o =>
{
    o.BaseUrl = builder.Configuration["FlagSwift:BaseUrl"]!;   // your FlagSwift server; required
    o.ApiKey  = builder.Configuration["FlagSwift:ApiKey"]!;    // fs_srv_ or fs_admin_ key with evaluation:read
    o.Fallbacks = new Dictionary<string, object?> { ["new-checkout"] = false };
    o.SnapshotPath = "/var/cache/myapp/flagswift.json";         // optional: survive restarts while the server is down
});

Then inject IFlagSwiftClient wherever you need it.

csharp
app.MapGet("/checkout", (IFlagSwiftClient flags, ClaimsPrincipal user) =>
    flags.IsEnabled("new-checkout", FlagUser.FromClaimsPrincipal(user, accountClaim: "tenant"))
        ? Results.Ok("new") : Results.Ok("old"));

Startup never blocks for long

The hosted service waits at most InitTimeout (5 seconds). StartAsync then returns false without throwing, and evaluation serves the snapshot, the bootstrap or your fallbacks while the fetch carries on in the background.

Without dependency injection#

In a console app or a script, create the client yourself and dispose it when you are done.

csharp
using var client = new FlagSwiftClient(new FlagSwiftOptions
{
    BaseUrl = "https://flags.example.com",
    ApiKey = key,
});
await client.StartAsync();   // fetch and start polling; returns false on failure, never throws

Connection options#

ApiKey and BaseUrl are required. Everything else has a default.

Common properties of FlagSwiftOptions
PropertyTypeDescription
ApiKey, BaseUrl*stringA server or admin key with evaluation:read, and your server address.
Environmentstring?Falls back to the FLAGSWIFT_ENVIRONMENT variable. Only for project-wide keys.
RefreshIntervalTimeSpanHow often to check for changes. Default 30 seconds. Zero or negative turns polling off.
FallbacksIDictionary<string, object?>A bool for plain flags, anything else for a value. Served for unknown flags and before anything loads.
SnapshotPathstring?File that keeps the last configuration across restarts (atomic, owner-only).
BootstrapConfigPayload?A saved payload to start from.
InitTimeout, TimeoutTimeSpanThe longest StartAsync waits, and per request. Default 5 seconds each.
MaxRetriesintDefault 3.
AutoExposuresboolQueue an exposure on every single-flag read. Default false.
OnError, OnUpdateActionCallbacks. They must not block.

Check flags#

A FlagUser says who is asking, and a plain string converts to one implicitly. A flag the server does not know gives your Fallbacks value, then false. Evaluation never throws.

csharp
var user = new FlagUser
{
    Identifiers = new[] { "user-42" },
    Accounts = new[] { "acme" },
    Attributes = new Dictionary<string, object?> { ["plan"] = "pro" },
};

if (flags.IsEnabled("new-checkout", user))
{
    // new flow
}

bool quick = flags.IsEnabled("new-checkout", "user-42");        // a string converts to a user
bool beta  = flags.IsEnabled("beta-banner", user, fallback: true); // your default if not found

EvaluationResult result = flags.Evaluate("new-checkout", user);  // Enabled, Reason, Found, Variant, Value

Guard a route with an attribute#

On an MVC controller or action, [RequireFlag] answers 404 when the flag is off for the signed-in user. Set StatusCode to change it.

csharp
[RequireFlag("new-checkout")]
public class CheckoutController : Controller { /* ... */ }

[RequireFlag("beta-reports", StatusCode = 403)]
public IActionResult Beta() => View();

The attribute builds the user from HttpContext.User with FlagUser.FromClaimsPrincipal, so an anonymous request gets the “off” side of a percentage rollout.

Check variants and values#

A flag can serve a named variant, such as a button colour or a plan limit. GetVariant gives its key and GetValue<T> gives what it carries, or the boolean for a plain flag.

csharp
string? variant = flags.GetVariant("checkout-layout", user);       // "compact", "wide" or null
int limit = flags.GetValue<int>("seat-limit", user, 5);            // the variant's value, or 5

var all = flags.EvaluateAll(user);                                 // a result per flag

Describe the person#

Percentage rollouts bucket on the first identifier. FlagUser.FromClaimsPrincipal(principal, accountClaim?, attributeClaims?) reads the identifier from the NameIdentifier or sub claim, an account from the claim you name, and attributes from any claims you list. FlagUser.Id("id") builds a user from one identifier, and FlagUser.Anonymous has none. Attributes feed targeting rules and never leave your server.

csharp
var user = FlagUser.FromClaimsPrincipal(
    httpContext.User,
    accountClaim: "tenant",
    attributeClaims: new[] { "plan", "country" });

Offline and errors#

The .NET SDK polls and has no real-time stream. Once a configuration has loaded, from the server, a snapshot or a bootstrap, evaluation is purely local. It keeps working with no internet and through a FlagSwift outage, and it never throws.

What happens when something goes wrong
SituationDescription
A refresh failsThe last good configuration and its ETag stay. The failure goes to OnError and shows in Status, and polling backs off up to five minutes. The next success resets it.
First load, nothing storedYou get Bootstrap or snapshot data, then your Fallbacks, then false. StartAsync waits at most InitTimeout and returns false without throwing.
Restart during an outageWith SnapshotPath the saved file is loaded in the constructor, before any network call. A missing, corrupt or incompatible file is ignored. The ETag is not saved, so the first fetch after a restart is a full response.
Server on an unknown hashVersionThe payload is refused rather than silently putting people in the wrong bucket.
Reading the stateclient.Status has LastError, ErrorCount, ConsecutiveFailures, FlagCount and LastFetch.

Outcome analytics#

Report what people saw and what they did so FlagSwift can compare variants. Nothing is sent unless you call these or set AutoExposures, and only the person's identifier, the flag, the variant and the event name leave your service.

csharp
client.TrackExposure("button-colour", user);   // this person was shown the flag's current outcome
client.Track("purchase", user, 19.99);          // what they did; the value is optional
await client.FlushAnalyticsAsync();             // send what is queued now and wait

The hosted service flushes on shutdown, and Dispose() flushes for up to 3 seconds. See Outcomes for how results are read in the console.

Reference#

Packages FlagSwift and FlagSwift.Extensions.DependencyInjection, .NET 8 or newer. Register the client as a singleton; a hosted service loads the configuration at startup, and a failed first fetch does not stop the app.

FlagSwiftOptions
PropertyTypeDescription
ApiKey, BaseUrl*stringA server or admin key with evaluation:read, and your server address.
Environmentstring?Falls back to the FLAGSWIFT_ENVIRONMENT variable.
RefreshIntervalTimeSpanDefault 30s. Zero or negative disables polling.
InitTimeoutTimeSpanDefault 5s. StartAsync then returns false without throwing and evaluation serves Bootstrap, the snapshot or Fallbacks while the fetch carries on.
TimeoutTimeSpanPer request. Default 5s.
MaxRetriesintDefault 3.
FallbacksIDictionary<string, object?>A bool for plain flags; anything else is a value.
BootstrapConfigPayload?A saved payload (see Snapshot).
SnapshotPathstring?File that keeps the last configuration (atomic, owner-only).
ReportErrorsboolDefault true.
OnError, OnUpdateActionMust not block.
TimeProvider, Delay, PollDelay, RandomSourcetest hooksReplace the clock, retry delay, poll wait and jitter.
FlagSwiftClient members
MemberDescription
new FlagSwiftClient(options, HttpClient? = null)IDisposable. Implements IFlagSwiftClient.
Task<bool> StartAsync(ct)Loads and starts background polling.
Task<bool> RefreshAsync(ct)Fetch now.
bool IsEnabled(flagKey, FlagUser? user = null, bool? fallback = null)A string converts to a user implicitly.
EvaluationResult Evaluate(flagKey, user)Enabled, Reason, Variant, Value (JsonElement?), Found, HasVariant and ValueAs<T>(fallback).
string? GetVariant(flagKey, user)The variant key.
T? GetValue<T>(flagKey, user, T? fallback)Variant value or boolean.
EvaluateAll(user)A result per flag.
TrackExposure(flag, user) / Track(event, user, value?)Report the outcome a person got and what they then did. Never throw. Track sends the person's pending exposures first.
FlushAnalyticsAsync()Sends what is queued now and waits. AutoExposures = true queues an exposure on every single-flag read (default false).
FlagKeys, Snapshot, StatusKnown keys, the loaded payload, and ClientStatus (Initialized, Environment, Version, FlagCount, LastFetch, LastError, ErrorCount, ConsecutiveFailures, Analytics).
Dispose()Stops polling.
Other .NET types
TypeDescription
FlagUserIdentifiers, Accounts, Devices and Attributes. FlagUser.Id(string), FlagUser.Anonymous and FlagUser.FromClaimsPrincipal(principal, accountClaim?, attributeClaims?).
FlagReasonString constants for every reason, for example FlagReason.RolloutIn.
FlagSwiftExceptionCode, Status and Retryable.
services.AddFlagSwift(options => ...)Registers the client as a singleton, IFlagSwiftClient, and the hosted service.
[RequireFlag("name")]MVC action filter. Answers 404 when the flag is off; set StatusCode to change it.

Not yet compiled

The .NET SDK has not been compiled or run, and the Laravel package has only been tested against stand-ins for Laravel. Treat both as unverified until you run their tests.