> ## Documentation Index
> Fetch the complete documentation index at: https://docs.westyx.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# .NET SDK - Getting started with ASP.NET Core

> From an empty solution to an ASP.NET Core endpoint that reads a Nexus config, a secret and a feature flag.

This page takes an empty Visual Studio solution to a running ASP.NET Core application that reads a
config, a secret and a feature flag from Nexus - and picks up a change made in the console without a
restart. It takes about ten minutes.

## What you need

* The **.NET 10 SDK** (or later), and Visual Studio, Rider or the `dotnet` CLI.
* A Nexus **service** with a **secret key** (`wxs_...`) and its **endpoint**
  (`https://<slug>.westyx.dev`) - see [Create a service](https://docs.westyx.dev/how-to/create-service.md). The endpoint is on
  the service's page in the console; the key is shown once, when you create it.
* In that service, three values to read:

| Kind | Key | Value |
| - | - | - |
| Config | `checkout.currency` | `"EUR"` |
| Config | `checkout.max_items` | `25` |
| Secret | `payment.api_key` | anything, e.g. `sk_test_123` |
| Flag | `new.checkout` | on |

## 1. Create the project

> [tab] Visual Studio
>
> In your solution, right-click the solution in **Solution Explorer** and choose **Add > New
> Project**. Pick **ASP.NET Core Empty**, name it `Checkout`, and choose **.NET 10.0**.

> [tab] dotnet CLI
>
> From the solution folder:
>
> ```sh theme={null}
> dotnet new web -n Checkout
> dotnet sln add Checkout
> ```

Any ASP.NET Core project works the same way - a Web API or MVC project only adds its own endpoints.

## 2. Add the package source and the packages

The packages are on the Westyx GitLab NuGet feed, which is public - no token is needed. Put a
`nuget.config` next to your solution file and commit it, so every machine and your CI find the feed:

```xml theme={null}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="westyx-nexus"
         value="https://gitlab.com/api/v4/projects/81978985/packages/nuget/index.json" />
  </packageSources>
</configuration>
```

Then add two packages to the `Checkout` project:

> [tab] Visual Studio
>
> Right-click the project, **Manage NuGet Packages**, set **Package source** to `westyx-nexus`
> (or **All**), and install `WestyxNexus.Extensions.Configuration` and
> `WestyxNexus.Extensions.DependencyInjection`. Both bring in the core `WestyxNexus` package.

> [tab] dotnet CLI
>
> ```sh theme={null}
> cd Checkout
> dotnet add package WestyxNexus.Extensions.Configuration
> dotnet add package WestyxNexus.Extensions.DependencyInjection
> ```

| Package | Gives you |
| - | - |
| `WestyxNexus.Extensions.Configuration` | `builder.AddWestyxNexus(...)` - Nexus configs in `IConfiguration`, and the client in the container |
| `WestyxNexus.Extensions.DependencyInjection` | `AddWestyxNexusSecrets<T>()` - secrets bound to `IOptions<T>` |

## 3. Tell the application where Nexus is

The endpoint is not a secret, so it goes in `appsettings.json`:

```json theme={null}
{
  "Nexus": {
    "BaseUrl": "https://<slug>.westyx.dev"
  }
}
```

The key is a secret, so it stays out of the repository. For development, keep it in
[user secrets](https://learn.microsoft.com/aspnet/core/security/app-secrets):

> [tab] Visual Studio
>
> Right-click the project, **Manage User Secrets**, and add:
>
> ```json theme={null}
> {
>   "Nexus": {
>     "ApiKey": "wxs_..."
>   }
> }
> ```

> [tab] dotnet CLI
>
> ```sh theme={null}
> dotnet user-secrets init
> dotnet user-secrets set "Nexus:ApiKey" "wxs_..."
> ```

In production, set the same value as the environment variable `Nexus__ApiKey`, or skip the key
entirely with [workload identity](#in-production).

## 4. Write `Program.cs`

Replace the contents of `Program.cs`:

```csharp theme={null}
using Microsoft.Extensions.Options;
using Westyx.Nexus;

var builder = WebApplication.CreateBuilder(args);

// One Nexus client: configs in IConfiguration, the client and secrets in the container.
builder.AddWestyxNexus(new NexusConfig
{
    BaseUrl = builder.Configuration["Nexus:BaseUrl"],
    ApiKey  = builder.Configuration["Nexus:ApiKey"],
});

// Nexus configs "checkout.currency" and "checkout.max_items".
builder.Services.Configure<CheckoutOptions>(builder.Configuration.GetSection("checkout"));

// Nexus secret "payment.api_key" - bound without entering IConfiguration.
builder.Services.AddWestyxNexusSecrets<PaymentOptions>("payment");

var app = builder.Build();

app.MapGet("/checkout", (
    IOptionsMonitor<CheckoutOptions> checkout,
    IOptionsMonitor<PaymentOptions> payment,
    NexusClient nexus) =>
    TypedResults.Ok(new CheckoutStatus(
        Currency:          checkout.CurrentValue.Currency,
        MaxItems:          checkout.CurrentValue.MaxItems,
        PaymentConfigured: payment.CurrentValue.ApiKey.Length > 0,
        NewCheckout:       nexus.GetFlag("new.checkout"))));

app.Run();

public sealed class CheckoutOptions
{
    public string Currency { get; set; } = "EUR";

    [ConfigurationKeyName("max_items")]
    public int MaxItems { get; set; } = 10;
}

public sealed class PaymentOptions
{
    public string ApiKey { get; set; } = "";
}

public sealed record CheckoutStatus(string Currency, int MaxItems, bool PaymentConfigured, bool NewCheckout);
```

What each part does:

* **`builder.AddWestyxNexus(...)`** creates one client, runs the first sync before the application
  starts, and keeps it current over a live connection that delivers a change within milliseconds.
  It is disposed with the application.
* **Configs** arrive in `IConfiguration` with `:` as the separator, so `checkout.currency` is
  `checkout:currency` and binds like any other section. `IConfiguration` matches property names
  case-insensitively but not across an underscore, which is what `[ConfigurationKeyName]` is for.
* **Secrets** do not enter `IConfiguration`, so a configuration dump cannot print them.
  `AddWestyxNexusSecrets<T>("payment")` binds every secret under `payment.` to `PaymentOptions`,
  and maps `api_key` to `ApiKey` itself. Keep the options type a `class`: a `record` prints its
  values from `ToString()` - see [Secrets binding](https://docs.westyx.dev/sdks/dotnet/secrets-binding.md).
* **Flags** are read from the client: `GetFlag` answers from memory, with no network call.
* **`IOptionsMonitor<T>`** is what sees a change without a restart; `IOptions<T>` keeps the value
  from startup.

## 5. Run it

Start the project (F5 in Visual Studio, or `dotnet run`) and open `/checkout` on the address it
prints (`Now listening on: http://localhost:<port>`):

```sh theme={null}
curl http://localhost:<port>/checkout
```

```json theme={null}
{"currency":"EUR","maxItems":25,"paymentConfigured":true,"newCheckout":true}
```

Now change `checkout.max_items` or switch `new.checkout` off in the console, and call the endpoint
again: the new value is there, with no restart.

## If it does not start

The first sync runs before the application starts, so a wrong setting stops it at startup rather
than on the first request:

| Error at startup | Cause |
| - | - |
| `ArgumentException: BaseUrl is required - set it or set WESTYX_SERVICE_ENDPOINT.` | `Nexus:BaseUrl` is missing from `appsettings.json` |
| `ArgumentException: ApiKey or Wif must be set.` | The key is not set. User secrets load only in the `Development` environment - check `ASPNETCORE_ENVIRONMENT` |
| `ArgumentException: BaseUrl must use https ...` | The endpoint starts with `http://`; plain http is accepted only for `localhost` |
| `NexusInitException: Initial sync failed: Unauthorized ...` | The key is wrong, revoked, or belongs to another service |
| `NexusInitException: Initial sync failed: Resource not found ...` | The slug in the endpoint is wrong |
| `Unable to find package WestyxNexus...` | The `westyx-nexus` source is missing - check `nuget.config` |

The full list is in [Error handling](https://docs.westyx.dev/sdks/dotnet/error-handling.md).

## In production

* **The key** comes from the environment - `Nexus__ApiKey` overrides user secrets and
  `appsettings.json` - or from whatever secret store already feeds your `IConfiguration`.
* **Better: no key at all.** On Kubernetes, EKS, AKS, GKE and Azure, the SDK can prove the
  workload's identity instead. Set `Wif` and drop `ApiKey`:

  ```csharp theme={null}
  builder.AddWestyxNexus(new NexusConfig
  {
      BaseUrl = builder.Configuration["Nexus:BaseUrl"],
      Wif     = new WifConfig { Enabled = true },
  });
  ```

  See [Workload identity](https://docs.westyx.dev/sdks/dotnet/workload-identity.md) for the trust policy it needs.
* **Locally without a key:** run `westyx dev setup --service=<name>` once. It stores a developer
  credential for the service, and the same `Wif` configuration finds it on your machine - see
  [Local development](https://docs.westyx.dev/sdks/dotnet/workload-identity.md#local-development-developer-wif).

## Which call to use

`builder.AddWestyxNexus(config)` is the right call for most ASP.NET Core applications. The others
serve one side only:

| You want | Call | Package |
| - | - | - |
| Configs in `IConfiguration`, plus secrets, flags or the client injected | `builder.AddWestyxNexus(config)` | `WestyxNexus.Extensions.Configuration` |
| Secrets, flags or the client injected, no configs in `IConfiguration` | [`builder.Services.AddWestyxNexus(...)`](https://docs.westyx.dev/sdks/dotnet/dependency-injection) | `WestyxNexus.Extensions.DependencyInjection` |
| Configs in `IConfiguration`, nothing else | [`builder.Configuration.AddWestyx(config)`](https://docs.westyx.dev/sdks/dotnet/aspnetcore-configuration) | `WestyxNexus.Extensions.Configuration` |
| No host at all - a console tool or a script | [`NexusClient.CreateAsync(config)`](#without-aspnet-core) | `WestyxNexus` |

Use one of them. Two calls create two clients, each with its own sync loop and live connection.
[Wiring the packages](https://docs.westyx.dev/sdks/dotnet/package-wiring.md) explains the trade-offs.

## Without ASP.NET Core

A console tool or a script creates the client itself and disposes it at the end:

```sh theme={null}
dotnet add package WestyxNexus
```

```csharp theme={null}
using Westyx.Nexus;

await using var client = await NexusClient.CreateAsync(new NexusConfig
{
    BaseUrl = "https://<slug>.westyx.dev",
    ApiKey  = Environment.GetEnvironmentVariable("NEXUS_API_KEY"),
});

var (currency, found) = client.GetConfig("checkout.currency");
string paymentKey     = client.GetSecret("payment.api_key");
bool newCheckout      = client.GetFlag("new.checkout");

Console.WriteLine($"{(found ? currency!.Value.GetString() : "unset")}, new checkout: {newCheckout}");
```

A long-running process calls `client.ConnectStream()` after creating the client to receive changes
as they happen.

## Next

> [card] [Feature management](https://docs.westyx.dev/sdks/dotnet/feature-management.md)
>
> Nexus flags through `IFeatureManager` and `[FeatureGate]`.

> [card] [OpenFeature](https://docs.westyx.dev/sdks/dotnet/openfeature.md)
>
> The vendor-neutral flag API, with per-user targeting.

> [card] [Workload identity](https://docs.westyx.dev/sdks/dotnet/workload-identity.md)
>
> Authenticate without a static key.

> [card] [Configuration](https://docs.westyx.dev/sdks/dotnet/configuration.md)
>
> Every `NexusConfig` option.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.