1

我是 C# 世界的新手。我有一个项目,我需要从 700 多个订阅中收集所有区域的 Azure 计算使用配额。我使用 PowerShell (Get-AzVMusage) 轻松完成了它。

我必须使用 C# 来完成。我想我需要使用 Rest API。(我对实现这一目标的另一种方式持开放态度)。

Azure 休息 API:GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/usages?api-version=2019-12-01

如何使用上述 Rest API 获取结果?一旦我从这个 Rest API 获得结果,我就可以将我的业务逻辑放在它上面来执行数据聚合,并通过 700 多个订阅循环它并将数据转储到 SQL-MI 中。

4

2 回答 2

2

我用谷歌搜索并从下面的网址找到了方法。

https://docs.microsoft.com/en-us/archive/blogs/benjaminperkins/how-to-securely-connect-to-azure-from-c-and-run-rest-apis MSDN 论坛

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;

namespace AzureCapacityUsage
{
    class Program
    {
        static async Task Main()
        {            
            try 
            {
                string token = await GetAccessToken(TenantID,ClientID,Password); 
                await GetResults(token);              
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception: {ex.Message}");
            }
        }

        private static async Task<string> GetResults(string token)
        {
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://management.azure.com/subscriptions/")
            };

            string URI = $"{SubscriptionGUID}/providers/Microsoft.Compute/locations/{Region}/usages?api-version=2019-12-01";

            httpClient.DefaultRequestHeaders.Remove("Authorization");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            HttpResponseMessage response = await httpClient.GetAsync(URI);

            var HttpsResponse = await response.Content.ReadAsStringAsync();
            var JSONObject =  JsonConvert.DeserializeObject<object>(HttpsResponse);
            
            Console.WriteLine(JSONObject);
            var JSONObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(JSONObject);
            return response.StatusCode.ToString();

        }
        private static async Task<string> GetAccessToken(string tenantId, string clientId, string clientKey)
        {
            Console.WriteLine("Begin GetAccessToken");

            string authContextURL = "https://login.windows.net/" + tenantId;
            var authenticationContext = new AuthenticationContext(authContextURL);
            var credential = new ClientCredential(clientId, clientKey);
            var result = await authenticationContext

            .AcquireTokenAsync("https://management.azure.com/", credential);
            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }
            string token = result.AccessToken;
            return token;
        }
    }
}

于 2020-05-23T00:11:05.993 回答
0

System.Net.HttpClient你的朋友在这里吗:

using System.Net.Http;
using System.Threading.Tasks;

namespace Sandbox
{
    public class SampleCall
    {
        static async Task<string> CallApi()
        {
            var subscriptionId = "subscriptionIdHere";
            var location = "locationHere";
            var uri = $"https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/usages?api-version=2019-12-01";

            using var client = new HttpClient();
            var response = await client.GetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }

            return string.Empty;
        }
    }
}

用法 :

var content = await SampleCall.CallApi();
于 2020-05-22T21:54:26.970 回答