如何通过C#获取Azure Log Analytics工作区的工作区ID

时间:2019-07-04 05:50:15

标签: azure

如何通过C#获取Azure中Log Analytics工作区的工作区ID?

enter image description here

2 个答案:

答案 0 :(得分:0)

似乎没有Log Analytics C#SDK来获取工作区ID,我的解决方法是获取访问令牌vai Microsoft.Azure.Services.AppAuthentication,然后调用REST API Workspaces - GetcustomerId响应中是您需要的工作区ID。

我的工作示例:

using Microsoft.Azure.Services.AppAuthentication;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace ConsoleApp6
{
    class Program
    {

        static void Main(string[] args)
        {
            CallWebAPIAsync().Wait();

        }

        static async Task CallWebAPIAsync()
        {
            AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
            string accessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/").Result;
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
                client.BaseAddress = new Uri("https://management.azure.com/");


                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //GET Method  
                HttpResponseMessage response = await client.GetAsync("subscriptions/<subscription id>/resourcegroups/<resource group name>/providers/Microsoft.OperationalInsights/workspaces/<workspace name>?api-version=2015-11-01-preview");
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine(response.Content.ReadAsStringAsync().Result);
                }
                else
                {
                    Console.WriteLine("Internal server Error");
                }
            }
        }
    }
}

enter image description here

有关身份验证的更多详细信息,请查看此link

答案 1 :(得分:0)

此后,我发现OperationalInsightsManagementClient类也可以使用。

var client = new OperationalInsightsManagementClient(GetCredentials()) {SubscriptionId = subscriptionId};
return (await client.Workspaces.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName))
    .Body
    .Select(w => w.CustomerId)
    .FirstOrDefault();