Follow a specific user in Application Insights .NET Core edition

In 2016 I wrote how to track a specific user in Application Insights which has been very useful in tracking down production issues. Now we are starting to upgrade our project to .NET Core so I wanted to share how to do this in .NET Core. In .NET Core you can use the same method, the ITelemetryInitializer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class AuthenticatedUserInitializer : ITelemetryInitializer
{
private IHttpContextAccessor _httpContextAccessor;

public AuthenticatedUserInitializer(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException("httpContextAccessor");
}
public void Initialize(ITelemetry telemetry)
{
var httpContext = _httpContextAccessor.HttpContext;
if (httpContext?.User?.Identity?.Name != null && httpContext.User.Identity.IsAuthenticated == true)
{
telemetry.Context.User.AuthenticatedUserId = httpContext.User.Identity.Name;
telemetry.Context.User.AccountId = httpContext.User.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?.Value ?? telemetry.Context.User.AccountId;
}
}
}

The interface is the same. To get access to the users information we need to access the user in the HttpContext. In .NET Core you get access to the HttpContext through the “IHttpContextAccessor” interface. Depending on the setup of your identity you can select the required information. We use our users email address (which is accessed through Identity.Name) as the AuthenticatedUserId. For the AccountId we use the unique user id (Guid in our case). In case no userId is available we use the accountId generated by Application Insights.

Edit (9/12/2018):
The way you register Initializers has also changed in .NET Core:

1
2
3
4
5
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ITelemetryInitializer, AuthenticatedUserInitializer>();
services.AddApplicationInsightsTelemetry();
}

Share