How to get the Workspace ID of an Azure Log Analytics workspace via C#

前端 未结 2 1375
醉话见心
醉话见心 2021-01-07 01:55

How can I get the Workspace ID of a Log Analytics workspace in Azure via C#?

相关标签:
2条回答
  • 2021-01-07 02:21

    I've since found that the OperationalInsightsManagementClient class can be used as well.

    var client = new OperationalInsightsManagementClient(GetCredentials()) {SubscriptionId = subscriptionId};
    return (await client.Workspaces.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName))
        .Body
        .Select(w => w.CustomerId)
        .FirstOrDefault();
    
    0 讨论(0)
  • 2021-01-07 02:24

    It seems there is no Log Analytics C# SDK to get the Workspace ID, my workaround is to get the access token vai Microsoft.Azure.Services.AppAuthentication, then call the REST API Workspaces - Get, the customerId in the response is the Workspace ID which you need.

    My working sample:

    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");
                    }
                }
            }
        }
    }
    

    For more details about the authentication, you could take a look at this link.

    0 讨论(0)
提交回复
热议问题