我是 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 中。
我用谷歌搜索并从下面的网址找到了方法。
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;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)