.NET product analytics installation
At the moment, ASP.NET Core is the only supported platform for the PostHog .NET SDK. However, we do have experimental support for other platforms mentioned later in this document.
In your Program.cs (or Startup.cs for ASP.NET Core 2.x) file, add the following code:
Make sure to configure PostHog with your project API key, instance address, and optional personal API key. For example, in appsettings.json:
Note: If the host is not specified, the default host
https://us.i.posthog.comis 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:
You can find your project API key and instance address in the project settings page in PostHog.
Working with .NET Feature Management
PostHog.AspNetCore supports .NET Feature Management. 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.
Then, register your implementation in Program.cs (or Startup.cs):
With this in place, you can now use feature tag helpers in your Razor views:
Multivariate feature flags are also supported:
You can also use the FeatureGateAttribute to gate access to controllers or actions:
Experimental support for other platforms
The PostHog package is multi-targeted to support net8.0 and dotnetstandard2.1. This means it can be used in a wider range of projects than just ASP.NET Core. However, this support is experimental and not officially supported.
If you are using a different platform, you can install the PostHog package instead of PostHog.AspNetCore. This package does not depend on ASP.NET Core and can be used in any .NET project.
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:
If you're not using a builder (such as in a console application), you can do the following:
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:
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: