如何让Request事件携带已认证用户ID?
嘿,我看你已经搞定了后端遥测带上认证用户ID的部分,要是你是想让前端的遥测也同步这个用户标识,或者需要完善现有逻辑的话,我来给你梳理下解决方案:
首先先把你的自定义遥测初始化器代码补全并格式化,方便后续参考:
public class MyTelemetryInitializer : ITelemetryInitializer { public void Initialize(ITelemetry telemetry) { if (HttpContext.Current?.Session?["user"] != null) { // 假设你的UserModel包含Id属性 var user = (UserModel)HttpContext.Current.Session["user"]; // 设置认证用户ID到遥测上下文 telemetry.Context.User.AuthenticatedUserId = user.Id.ToString(); telemetry.Context.User.Id = user.Id.ToString(); // 额外添加自定义属性,方便在Azure门户快速筛选 telemetry.Properties["AuthenticatedUserId"] = user.Id.ToString(); } } }
一、让前端遥测也带上认证用户ID
如果你的前端用了Application Insights JS SDK,想要让前端事件也关联到同一个用户ID,可以用这两种方案:
方案1:后端渲染页面时直接注入(适合传统Web应用)
在你的页面模板(比如Razor视图、ASPX页面)中,当用户已认证时,直接把用户ID写到JS代码里,调用SDK的setAuthenticatedUserContext方法:
<!-- 先引入Application Insights JS SDK --> <script type="text/javascript"> var appInsights = window.appInsights || function(config){ function s(config){ t[config] = function(){ var i = arguments; t.queue.push(function(){ t[config].apply(t, i)})} } var t = { config:config}, r = document, f = window, e = "script", o = r.createElement(e), i, u; o.src = config.url || "https://az416426.vo.msecnd.net/scripts/b/ai.0.js"; r.getElementsByTagName(e)[0].parentNode.appendChild(o); t.cookie = r.cookie; t.queue = []; const methods = ["Event","Exception","Metric","PageView","Trace","Dependency"]; for(const m of methods) s("track"+m); s("setAuthenticatedUserContext"); s("clearAuthenticatedUserContext"); if(!config.disableExceptionTracking){ i = "onerror"; s("_"+i); u = f[i]; f[i] = function(config, r, f, e, o){ const s = u && u(config, r, f, e, o); return s !== !0 && t["_"+i](config, r, f, e, o), s; } } return t; }({ instrumentationKey: "你的仪表板密钥" }); window.appInsights = appInsights; <!-- 注入后端的用户ID --> @if (HttpContext.Current?.Session?["user"] != null) { var user = (UserModel)HttpContext.Current.Session["user"]; <text> appInsights.setAuthenticatedUserContext("@user.Id.ToString()"); </text> } </script>
页面加载后,前端发送的所有遥测事件都会自动带上这个用户ID,和后端事件可以关联起来。
方案2:API接口获取用户ID(适合单页应用)
如果是Vue/React这类SPA应用,可以在用户登录后,调用后端授权接口获取用户ID,再在前端设置:
后端API(ASP.NET示例):
[Authorize] [HttpGet("api/auth/user-id")] public IActionResult GetAuthenticatedUserId() { if (HttpContext.Session["user"] == null) return Unauthorized(); var user = (UserModel)HttpContext.Session["user"]; return Ok(new { UserId = user.Id.ToString() }); }
前端JS代码:
// 用户登录成功后调用该方法设置遥测用户ID async function setAppInsightsUser() { try { const response = await fetch('/api/auth/user-id', { credentials: 'include' }); if (!response.ok) throw new Error('获取用户信息失败'); const data = await response.json(); if (data.UserId) { appInsights.setAuthenticatedUserContext(data.UserId); } } catch (err) { console.error('设置遥测用户ID失败:', err); } } // 登录成功后触发 setAppInsightsUser();
二、确保后端初始化器正确注册
别忘了把自定义的MyTelemetryInitializer注册到Application Insights中,不然后端遥测也不会生效:
ASP.NET MVC(Global.asax):
protected void Application_Start() { // 其他初始化代码... TelemetryConfiguration.Active.TelemetryInitializers.Add(new MyTelemetryInitializer()); }
ASP.NET Core(Startup.cs):
public void ConfigureServices(IServiceCollection services) { services.AddApplicationInsightsTelemetry(); // 注册自定义初始化器 services.AddSingleton<ITelemetryInitializer, MyTelemetryInitializer>(); // 其他服务配置... }
这样不管是后端还是前端的遥测事件,都会带上认证用户ID,你就能在Azure门户里按用户筛选、关联查看所有事件啦~
内容的提问来源于stack exchange,提问作者sandwood
相关产品推荐
相关产品推荐

