You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Application Insights正确统计.NET Web API的API用户数量

解决Azure Application Insights用户计数不准确的问题

针对你遇到的多客户端访问Swagger但Users计数仅显示1的问题,核心原因是Application Insights识别用户依赖用户唯一标识,仅设置session.id不足以区分不同用户,以下是具体解决步骤:

  • 添加用户唯一标识字段
    Application Insights的用户统计依赖user_Id字段,你需要在OpenTelemetry的请求上下文里注入该标识。推荐通过中间件为匿名客户端生成并持久化唯一ID(比如用Cookie存储),示例代码如下:

    app.Use(async (context, next) =>
    {
        // 从Cookie获取用户ID,不存在则生成新的并持久化
        var userId = context.Request.Cookies["unique_user_id"];
        if (string.IsNullOrEmpty(userId))
        {
            userId = Guid.NewGuid().ToString();
            context.Response.Cookies.Append("unique_user_id", userId, 
                new CookieOptions { Expires = DateTimeOffset.Now.AddYears(1), HttpOnly = true });
        }
        // 将用户ID添加到OpenTelemetry活动标签
        var currentActivity = Activity.Current;
        if (currentActivity != null)
        {
            currentActivity.SetTag("user.id", userId);
        }
        await next();
    });
    

    这段代码会为每个首次访问的客户端生成唯一ID并存在Cookie中,后续请求会携带该ID,OpenTelemetry的Azure Monitor Exporter会自动将user.id映射为App Insights所需的user_Id字段。

  • 修正会话ID的设置方式
    你当前每次请求生成新的session.id是不合理的,会话ID应该在同一个客户端会话中保持一致(比如也存在Cookie里,会话过期后再生成新的)。不过用户计数的核心还是用户ID,会话ID主要用于会话统计,所以优先确保用户ID的正确设置。

  • 检查Exporter配置
    确认你的OpenTelemetry Azure Monitor Exporter配置没有覆盖用户标识的映射。默认情况下,user.id会被正确映射到App Insights的user_Id,如果有自定义的处理器,需要确保不会移除或修改这个标签。

内容的提问来源于stack exchange,提问作者Striker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:52:20