在.NET应用中使用PostHog
PostHog帮助您构建更好的产品。它能追踪用户行为,控制生产环境中的功能特性,并且现在支持.NET!
配置
要配置客户端SDK,您需要:
- 项目API密钥 - 来自PostHog仪表板
- 个人API密钥 - 用于本地评估(可选但推荐)
1
2
3
4
5
|
{
"PostHog": {
"ProjectApiKey": "phc_..."
}
}
|
使用密钥管理器存储个人API密钥:
1
2
|
dotnet user-secrets init
dotnet user-secrets set "PostHog:PersonalApiKey" "phx_..."
|
注册客户端
在Program.cs文件中调用AddPostHog扩展方法:
1
2
3
4
|
using PostHog;
var builder = WebApplication.CreateBuilder(args);
builder.AddPostHog();
|
使用方法
用户识别
1
2
3
4
5
6
7
8
9
10
11
12
13
|
await posthog.IdentifyAsync(
distinctId,
user.Email,
user.UserName,
personPropertiesToSet: new()
{
["phone"] = user.PhoneNumber ?? "unknown",
["email_confirmed"] = user.EmailConfirmed,
},
personPropertiesToSetOnce: new()
{
["joined"] = DateTime.UtcNow
});
|
事件捕获
1
2
3
4
5
6
|
posthog.Capture("some-distinct-id", "my-event");
posthog.Capture(
"some-distinct-id",
"user signed up",
new() { ["plan"] = "pro" });
|
功能标记
1
2
3
4
5
|
if (await posthog.IsFeatureEnabledAsync(
"new_user_feature",
"some-distinct-id")) {
// 功能标记已启用
}
|
使用本地评估时传递用户属性:
1
2
3
4
|
await posthog.IsFeatureEnabledAsync(
featureKey: "person-flag",
distinctId: "some-distinct-id",
personProperties: new() { ["plan"] = "pro" });
|
.NET功能管理
使用功能标记标签助手:
1
2
3
|
<feature name="my-feature">
<p>这是一个功能标记。</p>
</feature>
|
在控制器中使用FeatureGate属性:
1
2
3
4
|
[FeatureGate("my-feature")]
public class MyController : Controller
{
}
|
实现功能标记上下文提供程序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class MyFeatureFlagContextProvider(
IHttpContextAccessor httpContextAccessor)
: PostHogFeatureFlagContextProvider
{
protected override string? GetDistinctId() =>
httpContextAccessor.HttpContext?.User.Identity?.Name;
protected override ValueTask<FeatureFlagOptions> GetFeatureFlagOptionsAsync()
{
return ValueTask.FromResult(
new FeatureFlagOptions
{
PersonProperties = new Dictionary<string, object?>
{
["email"] = "some-test@example.com",
["plan"] = "pro"
},
OnlyEvaluateLocally = true
});
}
}
|
非ASP.NET Core使用
直接使用核心PostHog包:
1
2
3
4
5
|
using PostHog;
var services = new ServiceCollection();
services.AddPostHog();
var serviceProvider = services.BuildServiceProvider();
var posthog = serviceProvider.GetRequiredService<IPostHogClient>();
|
对于控制台应用,直接使用PostHogClient:
1
2
3
4
5
|
using System;
using PostHog;
var posthog = new PostHogClient(
Environment.GetEnvironmentVariable("PostHog__PersonalApiKey"));
|
示例和后续计划
posthog-dotnet GitHub仓库的samples目录包含多个示例项目。未来计划包括开发PostHog.Unity包,并欢迎社区贡献Unity示例项目。