C#查询ApplicationInsights遇问题:认证兼容与requests表识别失败
问题解决方案
一、ServiceClientCredentials转TokenCredential及DefaultAzureCredential的可行性
- DefaultAzureCredential完全可行,它是Azure SDK官方推荐的认证方式,支持Visual Studio登录、环境变量、托管标识等多种认证场景,适配性强。
- 若想复用已有的
ServiceClientCredentials,可通过自定义TokenCredential包装类实现转换,代码示例如下:
public class ServiceClientCredentialsTokenCredential : TokenCredential { private readonly ServiceClientCredentials _serviceCredentials; private readonly string _scope; public ServiceClientCredentialsTokenCredential(ServiceClientCredentials credentials, string scope) { _serviceCredentials = credentials; _scope = scope; } public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken) { var message = new HttpRequestMessage(); _serviceCredentials.ProcessHttpRequestAsync(message, cancellationToken).GetAwaiter().GetResult(); if (message.Headers.TryGetValues("Authorization", out var values)) { var authValue = values.FirstOrDefault(); if (!string.IsNullOrEmpty(authValue) && authValue.StartsWith("Bearer ")) { var token = authValue.Substring(7); // 解析令牌获取过期时间,这里简化为1小时有效期 return new AccessToken(token, DateTimeOffset.UtcNow.AddHours(1)); } } throw new InvalidOperationException("无法从ServiceClientCredentials获取Bearer令牌"); } public override ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken) { return new ValueTask<AccessToken>(GetToken(requestContext, cancellationToken)); } }
使用时:
// Log Analytics的scope var scope = "https://api.loganalytics.io/.default"; var tokenCredential = new ServiceClientCredentialsTokenCredential(serviceCredentials, scope); var logsClient = new LogsQueryClient(tokenCredential);
二、查询requests表报错400的修复
核心原因:调用QueryWorkspaceAsync时,直接写requests会被解析为Log Analytics工作区自身的表(该表不存在),而requests属于关联的Application Insights资源,需指定资源限定符。
修复方案二选一:
- 在工作区查询中指定AI资源
修改查询语句,用app('AI应用ID')限定表所属的Application Insights:
app('{_IntApplicationInsightsApplicationId}').requests | take 10
对应代码:
Response<LogsQueryResult> response = client.QueryWorkspaceAsync( _IntLogAnalyticsWorkspaceId, $"app('{_IntApplicationInsightsApplicationId}').requests | take 10", new QueryTimeRange(TimeSpan.FromDays(14))) .Result;
- 直接查询Application Insights资源
使用QueryApplicationInsightsAsync方法,无需指定工作区,直接查询AI资源的表:
Response<LogsQueryResult> response = client.QueryApplicationInsightsAsync( _IntApplicationInsightsApplicationId, "requests | take 10", new QueryTimeRange(TimeSpan.FromDays(14))) .Result;
内容的提问来源于stack exchange,提问作者Richard Barraclough
相关产品推荐
相关产品推荐

