PostHog.AspNetCore 1.0.0-beta.11

Prefix Reserved
This is a prerelease version of PostHog.AspNetCore.
dotnet add package PostHog.AspNetCore --version 1.0.0-beta.11                
NuGet\Install-Package PostHog.AspNetCore -Version 1.0.0-beta.11                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="PostHog.AspNetCore" Version="1.0.0-beta.11" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add PostHog.AspNetCore --version 1.0.0-beta.11                
#r "nuget: PostHog.AspNetCore, 1.0.0-beta.11"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install PostHog.AspNetCore as a Cake Addin
#addin nuget:?package=PostHog.AspNetCore&version=1.0.0-beta.11&prerelease

// Install PostHog.AspNetCore as a Cake Tool
#tool nuget:?package=PostHog.AspNetCore&version=1.0.0-beta.11&prerelease                

PostHog.AspNetCore

This is a client SDK for the PostHog API written in C#. This package depends on the PostHog package and provides additional functionality for ASP.NET Core projects.

[!WARNING]
This package is currently in a pre-release stage. We're making it available publicly to solicit feedback. While we always strive to maintain a high level of quality, use this package at your own risk. There will be many breaking changes until we reach a stable release.

Installation

Use the dotnet CLI to add the package to your project:

$ dotnet add package PostHog.AspNetCore

Configuration

Register your PostHog instance in Program.cs (or Startup.cs depending on how you roll):

var builder = WebApplication.CreateBuilder(args);
builder.AddPostHog();

Set your project API key using user secrets:

$ dotnet user-secrets set PostHog:ProjectApiKey YOUR_API_KEY

In most cases, that's all you need to configure!

If you're using the EU hosted instance of PostHog or a self-hosted instance, you can configure the HostUrl setting in appsettings.json:

{
  ...
  "PostHog": {
    "HostUrl": "https://eu.i.posthog.com"
  }
}

There are some more settings you can configure if you want to tweak the behavior of the client, but the defaults should work in most cases.

The available options are:

Option Description Default
HostUrl The URL of the PostHog instance. https://us.i.posthog.com
MaxBatchSize The maximum number of events to send in a single batch. 100
MaxQueueSize The maximum number of events to store in the queue at any time. 1000
FlushAt The number of events to enqueue before sending events to PostHog. 20
FlushInterval The interval in milliseconds between periodic flushes. 30 seconds

[!NOTE] The client will attempt to send events to PostHog in the background. It sends it every FlushInterval or when FlushAt events have been enqueued. However, if the network is down or if there's a spike in events, the queue could grow without restriction. The MaxQueueSize setting is there to prevent the queue from growing too large. When that number is reached, the client will start dropping older events. MaxBatchSize ensures that the /batch request doesn't get too large.

Docs

More detailed docs for using this library can be found at PostHog Docs for the .NET Client SDK.

Usage

Inject the IPostHogClient interface into your controller or page:

public class HomeController(IPostHogClient posthog) : Controller
{
    public IActionResult SignUpComplete()
    {
        var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        posthog.Capture(userId, "user signed up", new() { ["plan"] = "pro" });
        return View();
    }
}
public class IndexModel(IPostHogClient posthog) : PageModel
{
    public void OnGet()
    {
        var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        posthog.CapturePageView(userId, Request.Path.Value ?? "Unknown");
    }
}

Identity

Identify a user

See the Identifying users for more information about identifying users.

Identifying a user typically happens on the front-end. For example, when an authenticated user logs in, you can call identify to associate the user with their previously anonymous actions.

When identify is called the first-time for a distinct id, PostHog will create a new user profile. If the user already exists, PostHog will update the user profile with the new data. So the typical usage of IdentifyAsync here will be to update the person properties that PostHog knows about your user.

await posthog.IdentifyAsync(
    userId,
    new() 
    {
        ["email"] = "haacked@posthog.com",
        ["name"] = "Phil Haack",
        ["plan"] = "pro"
    });
Alias a user

Use the Alias method to associate one identity with another. This is useful when a user logs in and you want to associate their anonymous actions with their authenticated actions.

var sessionId = Request.Cookies["session_id"]; // Used for anonymous actions.
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; // Now we know who they are.
await posthog.AliasAsync(sessionId, userId);

Analytics

Capture an Event

Note that capturing events is designed to be fast and done in the background. You can configure how often batches are sent to the PostHog API using the FlushAt and FlushInterval settings.

posthog.Capture(userId, "user signed up", new() { ["plan"] = "pro" });
Capture a Page View
posthog.CapturePageView(userId, Request.Path.Value ?? "Unknown");
Capture a Screen View
posthog.CaptureScreen(userId, "Main Screen");

Feature Flags

Check if feature flag is enabled

Check if the awesome-new-feature feature flag is enabled for the user with the id userId.

var enabled = await posthog.IsFeatureEnabledAsync(userId, "awesome-new-feature");

Get a single Feature Flag

Some feature flags may have associated payloads.

if (await posthog.GetFeatureFlagAsync("awesome-new-feature", "some-user-id") is { Payload: {} payload })
{
    // Do something with the payload.
    Console.WriteLine($"The payload is: {payload}");
}

Get All Feature Flags

Using information on the PostHog server.

var flags = await posthog.GetAllFeatureFlagsAsync("some-user-id");

Overriding the group properties for the current user.

var flags = await posthog.GetAllFeatureFlagsAsync(
"some-user-id",
options: new AllFeatureFlagsOptions
{
    Groups =
    [
        new Group("project", "aaaa-bbbb-cccc")
        {
            ["$group_key"] = "aaaa-bbbb-cccc",
            ["size"] = "large"
        }
    ]
});
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net8.0

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.0-beta.11 75 2/17/2025
1.0.0-beta.10 40 2/15/2025
1.0.0-beta.9 33 2/14/2025
1.0.0-beta.8 35 2/14/2025
1.0.0-beta.7 94 2/14/2025
1.0.0-beta.6 34 2/13/2025
1.0.0-beta.5 57 2/11/2025
1.0.0-beta.4 54 2/10/2025
1.0.0-beta.3 38 2/6/2025
1.0.0-beta.2 24 2/6/2025
1.0.0-beta 45 2/5/2025
1.0.0-alpha.2 39 2/3/2025
1.0.0-alpha 62 2/2/2025