# .NET feature flags installation - Docs

The `PostHog` package supports any .NET platform that targets .NET Standard 2.1 or .NET 8+, including MAUI, Blazor, and console applications. The `PostHog.AspNetCore` package provides additional conveniences for ASP.NET Core applications such as streamlined registration, request-scoped caching, and integration with [.NET Feature Management](https://learn.microsoft.com/en-us/azure/azure-app-configuration/feature-management-dotnet-reference).

> **Note:** We actively test with ASP.NET Core. Other platforms should work but haven't been specifically tested. If you encounter issues, please [report them on GitHub](https://github.com/PostHog/posthog-dotnet/issues).

> **Not supported:** Classic UWP (requires .NET Standard 2.0 only). Microsoft has [deprecated UWP](https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/migrate-to-windows-app-sdk/migrate-to-windows-app-sdk-ovw) in favor of the Windows App SDK. For Unity projects, see our dedicated [Unity SDK](/docs/libraries/unity.md) (currently in beta).

Terminal

PostHog AI

```bash
dotnet add package PostHog.AspNetCore
```

In your `Program.cs` (or `Startup.cs` for ASP.NET Core 2.x) file, add the following code:

C#

PostHog AI

```csharp
using PostHog;
var builder = WebApplication.CreateBuilder(args);
// Add PostHog to the dependency injection container as a singleton.
builder.AddPostHog();
```

Make sure to configure PostHog with your project token, instance address, and optional personal API key. For example, in `appsettings.json`:

JSON

PostHog AI

```json
{
  "PostHog": {
    "ProjectApiKey": "<ph_project_token>",
    "HostUrl": "https://us.i.posthog.com"
  }
}
```

> **Note:** If the host is not specified, the default host `https://us.i.posthog.com` is used.

Use a secrets manager to store your personal API key. For example, when developing locally you can use the `UserSecrets` feature of the `dotnet` CLI:

Terminal

PostHog AI

```bash
dotnet user-secrets init
dotnet user-secrets set "PostHog:PersonalApiKey" "phx_..."
```

You can find your project token and instance address in the [project settings](https://app.posthog.com/project/settings) page in PostHog.

## Working with .NET Feature Management

`PostHog.AspNetCore` supports [.NET Feature Management](https://learn.microsoft.com/en-us/azure/azure-app-configuration/feature-management-dotnet-reference). This enables you to use the <feature /\> tag helper and the `FeatureGateAttribute` in your ASP.NET Core applications to gate access to certain features using PostHog feature flags.

To use feature flags with the .NET Feature Management library, you'll need to implement the `IPostHogFeatureFlagContextProvider` interface. The quickest way to do that is to inherit from the `PostHogFeatureFlagContextProvider` class and override the `GetDistinctId` and `GetFeatureFlagOptionsAsync` methods.

C#

PostHog AI

```csharp
public class MyFeatureFlagContextProvider(IHttpContextAccessor httpContextAccessor)
    : PostHogFeatureFlagContextProvider
{
    protected override string? GetDistinctId()
        => httpContextAccessor.HttpContext?.User.Identity?.Name;
    protected override ValueTask<FeatureFlagOptions> GetFeatureFlagOptionsAsync()
    {
        // In a real app, you might get this information from a
        // database or other source for the current user.
        return ValueTask.FromResult(
            new FeatureFlagOptions
            {
                PersonProperties = new Dictionary<string, object?>
                {
                    ["email"] = "some-test@example.com"
                },
                OnlyEvaluateLocally = true
            });
    }
}
```

Then, register your implementation in `Program.cs` (or `Startup.cs`):

C#

PostHog AI

```csharp
var builder = WebApplication.CreateBuilder(args);
builder.AddPostHog(options => {
    options.UseFeatureManagement<MyFeatureFlagContextProvider>();
});
```

With this in place, you can now use `feature` tag helpers in your Razor views:

HTML

PostHog AI

```html
<feature name="awesome-new-feature">
    <p>This is the new feature!</p>
</feature>
<feature name="awesome-new-feature" negate="true">
    <p>Sorry, no awesome new feature for you.</p>
</feature>
```

Multivariate feature flags are also supported:

HTML

PostHog AI

```html
<feature name="awesome-new-feature" value="variant-a">
    <p>This is the new feature variant A!</p>
</feature>
<feature name="awesome-new-feature" value="variant-b">
    <p>This is the new feature variant B!</p>
</feature>
```

You can also use the `FeatureGateAttribute` to gate access to controllers or actions:

C#

PostHog AI

```csharp
[FeatureGate("awesome-new-feature")]
public class NewFeatureController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}
```

## Using the core package without ASP.NET Core

If you're not using ASP.NET Core (for example, in a console application, MAUI app, or Blazor WebAssembly), install the `PostHog` package instead of `PostHog.AspNetCore`. This package has no ASP.NET Core dependencies and can be used in any .NET project targeting .NET Standard 2.1 or .NET 8+.

Terminal

PostHog AI

```bash
dotnet add package PostHog
```

The `PostHogClient` class must be implemented as a singleton in your project. For `PostHog.AspNetCore`, this is handled by the `builder.AddPostHog();` method. For the `PostHog` package, you can do the following if you're using dependency injection:

C#

PostHog AI

```csharp
builder.Services.AddPostHog();
```

If you're not using a `builder` (such as in a console application), you can do the following:

C#

PostHog AI

```csharp
using PostHog;
var services = new ServiceCollection();
services.AddPostHog();
var serviceProvider = services.BuildServiceProvider();
var posthog = serviceProvider.GetRequiredService<IPostHogClient>();
```

The `AddPostHog` methods accept an optional `Action<PostHogOptions>` parameter that you can use to configure the client.

If you're not using dependency injection, you can create a static instance of the `PostHogClient` class and use that everywhere in your project:

C#

PostHog AI

```csharp
using PostHog;
public static readonly PostHogClient PostHog = new(new PostHogOptions {
    ProjectApiKey = "<ph_project_token>",
    HostUrl = new Uri("https://us.i.posthog.com"),
    PersonalApiKey = Environment.GetEnvironmentVariable(
      "PostHog__PersonalApiKey")
});
```

## Debug mode

If you're not seeing the expected events being captured, the feature flags being evaluated, or the surveys being shown, you can enable debug mode to see what's happening.

To see detailed logging, set the log level to `Debug` or `Trace` in `appsettings.json`:

JSON

PostHog AI

```json
{
  "DetailedErrors": true,
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "PostHog": "Trace"
    }
  },
  ...
}
```

### Community questions

Ask a question

### Was this page useful?

HelpfulCould be better