c# - 从 C# 应用程序查询 Azure Log Analytics
问题描述
过去几天我一直在努力从 Azure Log Analytics 查询自定义日志。我一直在关注微软从https://dev.int.loganalytics.io/documentation/1-Tutorials/Direct-API提供的教程,但我一直收到 403。我将工作区的所有权限授予我的 Azure 应用程序 [ ![ALA 工作区上的 Azure 应用程序权限][1]][1] [1]:https://i.stack.imgur.com/xxT2A.png 这是我用来尝试查询 ALA 的简单应用程序代码工作区
static async Task Main(string[] args)
{
String tenantId = "??????????????????????????????????";
String applicationId = "??????????????????????????????????";";
String applictionSecretKey = "??????????????????????????????????";;
String token;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Dictionary<String, String> requestData = new Dictionary<String, String>();
requestData.Add("grant_type", "client_credentials");
requestData.Add("client_id", applicationId);
requestData.Add("client_secret", applictionSecretKey);
requestData.Add("resource", "https://api.loganalytics.io/");
FormUrlEncodedContent requestBody = new FormUrlEncodedContent(requestData);
var request = await client.PostAsync($"https://login.microsoftonline.com/{tenantId}/oauth2/token", requestBody);
var response = await request.Content.ReadAsStringAsync();
token = JsonConvert.DeserializeObject<dynamic>(response).access_token;
}
String workspaceId = "??????????????????????????????????";;
String query = JsonConvert.SerializeObject(new
{
query = "ApplicationLog_CL | take 10",
timespan = "PT12H"
});
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var postContent = new StringContent(query, Encoding.UTF8, "application/json");
var response = await client.PostAsync($"https://api.loganalytics.io/v1/workspaces/{workspaceId}/query", postContent);
HttpContent responseContent = response.Content;
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
Console.ReadKey();
}
我不断收到来自 ALA API 的 403 响应。任何线索我在这里缺少什么?
解决方案
根据您提供的教程,我在我的网站上进行了测试,效果很好。
以下是您可以排除故障的一些方法。
1.当您add role
进入时Access control
,您可以添加名称AIDemoApp
类似于教程的AAD注册应用程序。
并且在 AAD 中添加了 Log Analytics API 权限。
2.new MediaTypeWithQualityHeaderValue("application/json")
更改为new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")
。
3.在AAD中注册的应用中添加权限后,点击Grant Permission
。
推荐阅读
- android - 如何设置相机捕获请求的旋转?
- python - 使用 OpenCV 3.4.3 进行颜色检测
- android - 签署 App Bundle 基本模块和动态功能模块
- android - 位图 onDraw() 不更新
- angular - 根据第一个下拉菜单角度禁用第二个下拉菜单
- java - 我如何遍历这个示例 JSON 数组来获取问题名称、问题准确性和专业化名称
- visual-studio-code - VSCode 错误装饰默认为文本不透明度(而不是下划线波浪)
- amazon-web-services - 使用 AWS EKS 集群和 ELK 的流利位
- java - 为什么在第一次运行时不能从领域数据库中读取
- asp.net-mvc - 它是如何发生的。Identity Server4 用户登录页面重定向。重定向网址的目的