I am using .NET Core 3.1. I want to populate the User ID
property in Application Insights with the ASP.NET Core identity username. I got this article by Microsoft, but it is for the full .NET Framework. I also tried the following code given here (I changed claim to Identity)
public class TelemetryEnrichment : TelemetryInitializerBase
{
public TelemetryEnrichment(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
{
}
protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry)
{
telemetry.Context.User.AuthenticatedUserId =
platformContext.User?.Identity.Name ?? string.Empty;
}
}
but don't know how to include it in the pipeline. I tried services.AddSingleton<ITelemetryInitializer, TelemetryEnrichment>();
but it doesn't help. Application Insights is still showing its own User ID.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, ApplicationRole>(
options => {
options.Stores.MaxLengthForKeys = 128;
options.User.RequireUniqueEmail = true;
options.Password.RequiredLength = 8;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddRoles<ApplicationRole>()
.AddSignInManager<ApplicationSignInManager>();
services.AddControllersWithViews()
.AddNewtonsoftJson()
.AddRazorRuntimeCompilation();
services.AddRazorPages();
services.AddMvc(mvcOptions =>
{
mvcOptions.ModelBinderProviders.Insert(0, new ModelBinderProvider());
})
.AddRazorPagesOptions(options =>
{
options.Conventions.AddAreaPageRoute("Identity", "/Account/Login", "");
})
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddAntiforgery(options => options.HeaderName = "XSRF-TOKEN");
services.AddFlashMessage();
services.AddSingleton<IEmailUtility, EmailUtility>();
services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddApplicationInsightsTelemetry();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<ITelemetryInitializer, TelemetryEnrichment>();
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
var mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
}
To get the Application ID: From your Application Insights resource, click API Access. Copy the Application ID and paste it to the Application Insights Application ID field of your bot's settings.
You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);
Open your project in Visual Studio. Go to Project > Add Application Insights Telemetry. Choose Azure Application Insights, then select Next. Choose your subscription and Application Insights instance (or create a new instance with Create new), then select Next.
Application Insights defines a data model for distributed telemetry correlation. To associate telemetry with a logical operation, every telemetry item has a context field called operation_Id . This identifier is shared by every telemetry item in the distributed trace.
Answering my own question for completeness. The code given in the question works perfectly fine. I will just put it here again.
To get the ASP.NET Core identity username in your Application Insights, you need a custom telemetry initializer Please refer to original answer by @PeterBons here
public class TelemetryEnrichment : TelemetryInitializerBase
{
public TelemetryEnrichment(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
{
}
protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry)
{
telemetry.Context.User.AuthenticatedUserId =
platformContext.User?.Identity.Name ?? string.Empty;
}
}
Then you need to register it in your Startup.cs ConfigureServices
as below:
public void ConfigureServices(IServiceCollection services)
{
...
...
services.AddApplicationInsightsTelemetry();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<ITelemetryInitializer, TelemetryEnrichment>();
...
...
}
Remember to put AddApplicationInsightsTelemetry()
above the AddSingleton()
Once this is set up, the identity username is displayed under Auth User ID
property in Application Insights.
-- Update --
The identity username is now displayed under Auth Id
instead of Auth User ID
as stated above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With