gpt4 book ai didi

c# - 从 C# 应用程序查询 Azure Log Analytics

转载 作者:行者123 更新时间:2023-12-03 00:27:28 30 4
gpt4 key购买 nike

过去几天我一直在努力从 Azure Log Analytics 查询自定义日志。我一直在关注微软提供的教程 https://dev.int.loganalytics.io/documentation/1-Tutorials/Direct-API但我不断收到 403。我将工作区的所有权限授予了我的 Azure 应用程序[![ALA 工作区上的 Azure 应用程序权限][1]][1][1]:/image/xxT2A.png这是我用来尝试查询 ALA Workspace 的简单应用程序代码

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 响应。知道我在这里缺少什么吗?

最佳答案

根据tutorial你提供的,我在我的网站上测试过,效果很好。

以下是一些排除故障的方法。

1.当您在访问控制添加角色时,您可以像教程一样添加名称为AIDemoApp的AAD注册应用程序。

enter image description here

并在AAD中添加Log Analytics API权限。 enter image description here

2.将 new MediaTypeWithQualityHeaderValue("application/json") 更改为 new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")

3.在AAD中注册的应用中添加权限后,点击授予权限

enter image description here

关于c# - 从 C# 应用程序查询 Azure Log Analytics,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53915236/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com