如何在C#中调用Azure Rest API

5

我刚刚接触C#技术。 我有一个项目需要收集700多个订阅中所有区域的Azure计算使用配额。 我已经用PowerShell(Get-AzVMUsage)轻松完成了此任务。

现在我需要使用C#完成这个任务。 我猜我需要使用Rest API来实现它(但如果有其他方式也可以)。

Azure Rest 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中。

3个回答

7
我谷歌搜索并从以下网址找到了方法。 https://learn.microsoft.com/en-us/archive/blogs/benjaminperkins/how-to-securely-connect-to-azure-from-c-and-run-rest-apisMSDN论坛

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


有关更为实时的答案,请参阅约翰的帖子:https://dev59.com/trvoa4cB1Zd3GeqPySh5 - derekbaker783

3

Vinny的答案已经不再支持。从2022年12月开始,与AuthenticationContext一起使用的Microsoft.IdentityModel.Clients.ActiveDirectory Nuget将不再受支持。

我们可以使用Azure.Identity Nuget,然后用以下代码替换GetAccessToken方法...

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

    var credentials = new ClientSecretCredential(tenantId, clientId, clientKey);
    var result = await credentials.GetTokenAsync(new TokenRequestContext(new[] { "https://management.azure.com/.default" }), CancellationToken.None);
    return result.Token;
}

话虽如此,使用SDK可能会更容易。我写了一篇关于SDK和Rest API的博客文章,您可能会发现它很有用。


如果您能在这里包含使用语句,那将非常棒……它们总是让我感到困惑。 - Dan Ciborowski - MSFT

-2

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();

4
这个的认证组件在哪里?它非常重要。 - johnstaveley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接