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

ASP.NET Core中SQL依赖调用与请求的关联查询问题

问题描述

已正确配置ASP.NET Core应用记录请求对应的SQL调用,尝试通过Kusto查询找到与指定SQL调用关联的ASP.NET控制器请求,测试了两种关联方式:

// 按operation_Id关联
requests 
|where timestamp > start_time and timestamp < end_time
| join (dependencies
        | where ['type'] == "SQL" and data has "some-field-name-here" 
        ) on operation_Id

// 按operationParentId关联
requests 
|where timestamp > start_time and timestamp < end_time
| join (dependencies
        | where ['type'] == "SQL" and data has "some-field-name-here" 
        ) on $left.operation_Id = $right.operationParentId

第二种查询无结果,第一种查询返回的请求在对应控制器方法中并没有SQL调用代码,请问问题出在哪里?

分析与解决

关联逻辑误解

  1. operation_Id的作用:operation_Id是整个请求链路的全局唯一ID,同一链路内的所有requests、dependencies、traces都会共享这个ID。你用operation_Id关联时,会拉取整个链路中所有相关的请求,包括链路里的父级、同级请求,这就是为什么查到的请求里没有对应SQL代码——你关联到了链路中其他不直接触发SQL的请求。

  2. operationParentId的匹配错误:第二种查询的关联条件错误,SQL依赖的operationParentId是调用该SQL的组件的操作ID(比如中间业务服务的operation_Id),而非根控制器请求的operation_Id,所以直接用requests.operation_Id = dependencies.operationParentId无法匹配到结果。

正确的查询方式

方式1:通过全局链路ID定位根控制器请求

先找到目标SQL的链路ID,再筛选出该链路中的根请求(控制器请求):

// 定位目标SQL的依赖记录,提取全局链路ID
let targetSqlDeps = dependencies
| where timestamp > start_time and timestamp < end_time
| where type == "SQL" and data has "some-field-name-here"
| project operation_Id;

// 从链路中筛选根控制器请求(根请求的operationParentId通常为空)
requests
| where timestamp > start_time and timestamp < end_time
| where operation_Id in (targetSqlDeps.operation_Id)
| where isempty(operationParentId)
// 可通过name字段进一步筛选控制器请求(根据你的路由格式调整)
| where name matches regex @"^(GET|POST|PUT|DELETE) .*\/api\/.*"
| project timestamp, requestName = name, requestUrl = url, operation_Id

方式2:链式追溯父级操作

直接从SQL依赖向上追溯,找到对应的控制器请求:

dependencies
| where timestamp > start_time and timestamp < end_time
| where type == "SQL" and data has "some-field-name-here"
// 关联所有遥测数据,找到当前SQL的父级操作
| join kind=inner (union requests, dependencies) on $left.operationParentId == $right.id
// 筛选出父级中的请求类型(控制器请求)
| where $right.itemType == "request"
| project 
    requestTimestamp = $right.timestamp, 
    requestName = $right.name, 
    requestUrl = $right.url, 
    sqlStatement = $left.data

额外检查点

  • 遥测配置验证:确认已正确安装Microsoft.ApplicationInsights.AspNetCore包,并在Program.cs中添加builder.Services.AddApplicationInsightsTelemetry();,确保链路ID能正确传递。
  • 请求名称筛选:控制器请求的name字段通常格式为HTTP方法 /控制器/方法(比如GET WeatherForecast/Get),可通过该字段排除非控制器请求(如健康检查)。
  • 时间范围一致性:确保start_time和end_time同时覆盖SQL调用和对应请求的时间,避免因时间差导致关联失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 00:32:26