Skip to content

Latest commit

 

History

History
350 lines (259 loc) · 11.5 KB

File metadata and controls

350 lines (259 loc) · 11.5 KB

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.

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 token using user secrets:

$ dotnet user-secrets set PostHog:ProjectToken YOUR_PROJECT_TOKEN

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.

Local Evaluation

If you want to evaluate feature flags locally, you'll need to provide a personal API key for the PostHog API.

For local development, you can set the PostHog:PersonalApiKey setting in your user secrets:

$ dotnet user-secrets set PostHog:PersonalApiKey YOUR_PERSONAL_API_KEY

For production, we recommend using a secrets manager or environment variables to set the PostHog:PersonalApiKey setting.

Docs

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

Usage

Frontend-to-backend request context

If your frontend sends PostHog JS request context headers, import the ASP.NET Core helpers and add the middleware before routes that call PostHog:

using PostHog;
using PostHog.AspNetCore;

app.UsePostHogRequestContext();

This reads client-controlled X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID headers into a request-local analytics context. Installing the middleware opts the pipeline into request context extraction; individual PostHog calls use request-context identity only when they omit an explicit distinctId or call a parameterless request-context helper. Explicit distinct IDs always override request context. Captures inside the request can then omit distinctId:

using PostHog.AspNetCore;

posthog.Capture("checkout started");

These headers are client-controlled analytics context, not authentication. If X-POSTHOG-DISTINCT-ID is missing, normal captures become personless by default.

The request-context EvaluateFlagsAsync() overloads also use the current request context distinct ID. Use them for analytics-driven consistency with frontend flag evaluation, not authorization checks. For security-sensitive server branching, pass an authenticated distinct ID explicitly:

var flags = await posthog.EvaluateFlagsAsync(authenticatedUserId);

You can disable tracing header use while still collecting request metadata:

app.UsePostHogRequestContext(options =>
{
    options.UseTracingHeaders = false;
});

The middleware also adds request metadata such as $current_url, $request_method, $request_path, $user_agent, and $ip. $current_url omits the query string to avoid sending secrets such as OAuth codes, reset tokens, or signed URL parameters.

If your app is behind a proxy, configure ASP.NET Core forwarded headers before this middleware so $ip uses the normalized HttpContext.Connection.RemoteIpAddress value.

Unhandled downstream exception capture is disabled by default to avoid duplicate reporting if your app already captures exceptions elsewhere. Enable it explicitly to capture exceptions with the active request context and rethrow them. Exception capture uses the same request context identity/session/properties as regular captures:

app.UsePostHogRequestContext(options =>
{
    options.CaptureExceptions = true;
});

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"
        }
    ]
});

Evaluation contexts

Configure SDK-level feature flag evaluation contexts to only evaluate flags intended for this application, platform, or product area.

builder.Services.AddPostHog(options =>
{
    options.ProjectToken = "YOUR_PROJECT_TOKEN";
    options.EvaluationContexts = ["main-app", "api", "backend"];
});

Flags without evaluation contexts continue to evaluate for all SDKs. Flags with contexts evaluate only when at least one configured context matches.

Feature Management

PostHog.AspNetCore supports .NET Feature Management. This allows 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.

Setup

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.

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):

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

Usage

You can now use feature tag helpers in your Razor views:

<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:

<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:

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