feat: Add server-side request context support#198
Conversation
85697e0 to
118ff9c
Compare
posthog-dotnet Compliance ReportDate: 2026-05-18 18:06:40 UTC
|
| Test | Status | Duration |
|---|---|---|
| Request Payload.Request With Person Properties Device Id | ❌ | 44ms |
| Request Payload.Flags Request Uses V2 Query Param | ❌ | 22ms |
| Request Payload.Flags Request Hits Flags Path Not Decide | ❌ | 5ms |
| Request Payload.Flags Request Omits Authorization Header | ❌ | 4ms |
| Request Payload.Token In Flags Body Matches Init | ❌ | 5ms |
| Request Payload.Groups Round Trip | ❌ | 4ms |
| Request Payload.Groups Default To Empty Object | ❌ | 5ms |
| Request Payload.Person Properties Distinct Id Auto Populated When Caller Omits It | ❌ | 4ms |
| Request Payload.Disable Geoip False Propagates As Geoip Disable False | ❌ | 5ms |
| Request Payload.Disable Geoip Omitted Defaults To False | ❌ | 4ms |
| Request Payload.Flag Keys To Evaluate Contains Only Requested Key | ❌ | 5ms |
| Request Lifecycle.No Flags Request On Init Alone | ✅ | 3ms |
| Request Lifecycle.No Flags Request On Normal Capture | ✅ | 180ms |
| Request Lifecycle.Two Flag Calls Produce Two Remote Requests | ❌ | 6ms |
| Request Lifecycle.Mock Response Value Is Returned To Caller | ❌ | 5ms |
| Side Effect Events.Get Feature Flag Captures Feature Flag Called Event | ❌ | 4ms |
Failures
request_payload.request_with_person_properties_device_id
404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'
request_payload.flags_request_uses_v2_query_param
404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'
request_payload.flags_request_hits_flags_path_not_decide
404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'
request_payload.flags_request_omits_authorization_header
404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'
request_payload.token_in_flags_body_matches_init
404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'
request_payload.groups_round_trip
404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'
request_payload.groups_default_to_empty_object
404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'
request_payload.person_properties_distinct_id_auto_populated_when_caller_omits_it
404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'
request_payload.disable_geoip_false_propagates_as_geoip_disable_false
404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'
request_payload.disable_geoip_omitted_defaults_to_false
404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'
request_payload.flag_keys_to_evaluate_contains_only_requested_key
404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'
request_lifecycle.two_flag_calls_produce_two_remote_requests
404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'
request_lifecycle.mock_response_value_is_returned_to_caller
404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'
side_effect_events.get_feature_flag_captures_feature_flag_called_event
404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'
Prompt To Fix All With AIFix the following 4 code review issues. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 4
src/PostHog.AspNetCore/Tracing/PostHogTracingHeaders.cs:115-120
`$current_url` omits the query string. PostHog's other SDKs set `$current_url` to the full URL including query parameters (UTM tags, pagination state, etc.), so omitting it will cause analytics discrepancies. `request.QueryString.ToUriComponent()` returns an empty string when there is no query string, so appending it is always safe.
```suggestion
return string.Concat(
request.Scheme,
"://",
request.Host.ToUriComponent(),
request.PathBase.ToUriComponent(),
request.Path.ToUriComponent(),
request.QueryString.ToUriComponent());
```
### Issue 2 of 4
src/PostHog.AspNetCore/Tracing/PostHogTracingHeaders.cs:77-78
`StringValues.IsNullOrEmpty` returns `true` whenever `Count == 0` (or the single value is empty), so after it returns `false`, `Count` is always ≥ 1. The `values.ToString()` branch is therefore unreachable dead code.
```suggestion
return SanitizeValue(values[0]);
```
### Issue 3 of 4
src/PostHog.AspNetCore/Tracing/PostHogRequestContextMiddlewareExtensions.cs:20-23
When `app` is null, `return app!` uses the null-forgiving operator to push a `null` through a non-nullable return type. Any subsequent chained call on the result would throw a `NullReferenceException`. `ArgumentNullException.ThrowIfNull` is the idiomatic guard here and gives a better error message.
```suggestion
ArgumentNullException.ThrowIfNull(app);
```
### Issue 4 of 4
tests/UnitTests/PostHogContextTests.cs:103-123
`MissingDistinctIdCreatesPersonlessContext` and `ExplicitProcessPersonProfileOverridesPersonlessDefault` exercise the same method with different `properties` inputs and assert on the same output key — a good fit for a `[Theory]` per the project's preference for parameterised tests.
```suggestion
[Theory]
[InlineData(null, false)]
[InlineData(true, true)]
public void PersonlessContextSetsProcessPersonProfile(bool? explicitOverride, bool expectedValue)
{
var properties = explicitOverride.HasValue
? new Dictionary<string, object> { ["$process_person_profile"] = explicitOverride.Value }
: null;
var context = PostHogContextHelper.ResolveCaptureContext(distinctId: null, properties: properties);
Assert.True(Guid.TryParse(context.DistinctId, out _));
Assert.True(context.IsPersonless);
Assert.NotNull(context.Properties);
Assert.Equal(expectedValue, (bool)context.Properties["$process_person_profile"]);
}
```
Reviews (1): Last reviewed commit: "Move request context overloads to ASP.NE..." | Re-trigger Greptile |
73cb36d to
df0ca2f
Compare
| public static IApplicationBuilder UsePostHogRequestContext( | ||
| this IApplicationBuilder app, | ||
| Action<PostHogRequestContextOptions>? configure = null) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(app); |
There was a problem hiding this comment.
We typically avoid throwing, but this one seems unavoidable. If app is null, there's no easy way to recover.
Considering this would be called on initialization, avoiding an exception here could mask some serious issues.
haacked
left a comment
There was a problem hiding this comment.
Solid PR overall. A handful of non-blocking suggestions inline; the highest-leverage ones are the duplicate $session_id constant, the empty-string divergence across the three flag entrypoints, and the query-string secrets surface in $current_url.
|
@haacked did the review already so skipping until its good to go, happy to do a final review if needed otherwise his approval should be enough! |
|
This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, post a comment or remove the |
| this IPostHogClient client, | ||
| string eventName) | ||
| { | ||
| var checkedClient = NotNull(client); |
There was a problem hiding this comment.
this will crash the app, better to just return false instead, check the other callsites
💡 Motivation and Context
Add ASP.NET Core request-scoped PostHog context so server-side captures and exception events during a request can inherit useful request metadata and, when enabled, PostHog tracing headers (
X-PostHog-Distinct-Id,X-PostHog-Session-Id).This aligns .NET behavior with the server-side request context guidelines while keeping the context implementation internal to avoid expanding the public .NET API surface.
Middleware behavior:
UsePostHogRequestContextnow always wraps ASP.NET Core requests and applies request metadata ($current_url,$request_method,$request_path,$user_agent,$ip) to captures made during the request.options.UseTracingHeaders.HttpContext.Useris not treated as a PostHog distinct ID automatically.💚 How did you test it?
dotnet build PostHog.sln --no-restoredotnet test tests/UnitTests.AspNetCore/UnitTests.AspNetCore.csproj --no-restoredotnet test tests/UnitTests/UnitTests.csproj --no-restore --framework net8.0 --filter "FullyQualifiedName~PostHogContextTests|FullyQualifiedName~FeatureFlagEvaluationsTests"Note: full
UnitTestsnet8 currently has two unrelated exception stack-frame assertion failures in this environment.📝 Checklist
If releasing new changes
pnpm changesetto generate a changeset file