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:
public class AuthenticatedUserInitializer : ITelemetryInitializer
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.
The way you register Initializers has also changed in .NET Core:
public void ConfigureServices(IServiceCollection services)