.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
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#
dotnet add package FlagSwift
dotnet add package FlagSwift.Extensions.DependencyInjectionIt 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.
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.
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
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.
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 throwsConnection options#
ApiKey and BaseUrl are required. Everything else has a default.
| Property | Type | Description |
|---|---|---|
| ApiKey, BaseUrl* | string | A server or admin key with evaluation:read, and your server address. |
| Environment | string? | Falls back to the FLAGSWIFT_ENVIRONMENT variable. Only for project-wide keys. |
| RefreshInterval | TimeSpan | How often to check for changes. Default 30 seconds. Zero or negative turns polling off. |
| Fallbacks | IDictionary<string, object?> | A bool for plain flags, anything else for a value. Served for unknown flags and before anything loads. |
| SnapshotPath | string? | File that keeps the last configuration across restarts (atomic, owner-only). |
| Bootstrap | ConfigPayload? | A saved payload to start from. |
| InitTimeout, Timeout | TimeSpan | The longest StartAsync waits, and per request. Default 5 seconds each. |
| MaxRetries | int | Default 3. |
| AutoExposures | bool | Queue an exposure on every single-flag read. Default false. |
| OnError, OnUpdate | Action | Callbacks. 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.
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, ValueGuard 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.
[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.
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 flagDescribe 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.
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.
| Situation | Description |
|---|---|
| A refresh fails | The 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 stored | You get Bootstrap or snapshot data, then your Fallbacks, then false. StartAsync waits at most InitTimeout and returns false without throwing. |
| Restart during an outage | With 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 hashVersion | The payload is refused rather than silently putting people in the wrong bucket. |
| Reading the state | client.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.
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 waitThe 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.
| Property | Type | Description |
|---|---|---|
| ApiKey, BaseUrl* | string | A server or admin key with evaluation:read, and your server address. |
| Environment | string? | Falls back to the FLAGSWIFT_ENVIRONMENT variable. |
| RefreshInterval | TimeSpan | Default 30s. Zero or negative disables polling. |
| InitTimeout | TimeSpan | Default 5s. StartAsync then returns false without throwing and evaluation serves Bootstrap, the snapshot or Fallbacks while the fetch carries on. |
| Timeout | TimeSpan | Per request. Default 5s. |
| MaxRetries | int | Default 3. |
| Fallbacks | IDictionary<string, object?> | A bool for plain flags; anything else is a value. |
| Bootstrap | ConfigPayload? | A saved payload (see Snapshot). |
| SnapshotPath | string? | File that keeps the last configuration (atomic, owner-only). |
| ReportErrors | bool | Default true. |
| OnError, OnUpdate | Action | Must not block. |
| TimeProvider, Delay, PollDelay, RandomSource | test hooks | Replace the clock, retry delay, poll wait and jitter. |
| Member | Description |
|---|---|
| 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, Status | Known keys, the loaded payload, and ClientStatus (Initialized, Environment, Version, FlagCount, LastFetch, LastError, ErrorCount, ConsecutiveFailures, Analytics). |
| Dispose() | Stops polling. |
| Type | Description |
|---|---|
| FlagUser | Identifiers, Accounts, Devices and Attributes. FlagUser.Id(string), FlagUser.Anonymous and FlagUser.FromClaimsPrincipal(principal, accountClaim?, attributeClaims?). |
| FlagReason | String constants for every reason, for example FlagReason.RolloutIn. |
| FlagSwiftException | Code, 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