C#调用Azure REST API时,如何编程获取Azure Subscription ID?
Absolutely! You can fetch Azure Subscription IDs using the Azure Management REST API with your existing access token. Here's a step-by-step breakdown and code example to help you out:
Prerequisites
First, make sure your Azure AD application (the one you used to get the access token) has the Microsoft.Subscriptions/subscriptions/read permission assigned. You’ll need to add this permission from the Azure Portal’s App Registration section, and grant admin consent if required for your organization.
Step 1: Call the Azure Management API Endpoint
Use this REST endpoint to retrieve all subscriptions the authenticated identity has access to:
GET https://management.azure.com/subscriptions?api-version=2020-01-01
Step 2: C# Code Implementation
Here’s a complete example using HttpClient to send the request, authenticate with your access token, and parse the response:
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Newtonsoft.Json; // Helper classes to deserialize the API response public class SubscriptionResponse { public Subscription[] Value { get; set; } } public class Subscription { public string Id { get; set; } public string Name { get; set; } public string SubscriptionId { get; set; } public string TenantId { get; set; } } class Program { static async Task Main(string[] args) { string accessToken = "YOUR_VALID_ACCESS_TOKEN"; // Replace with your actual token string apiEndpoint = "https://management.azure.com/subscriptions?api-version=2020-01-01"; using (HttpClient client = new HttpClient()) { // Attach the access token to the request header client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); HttpResponseMessage response = await client.GetAsync(apiEndpoint); response.EnsureSuccessStatusCode(); // Throws an exception if the request fails // Parse the JSON response string responseContent = await response.Content.ReadAsStringAsync(); SubscriptionResponse subscriptionResponse = JsonConvert.DeserializeObject<SubscriptionResponse>(responseContent); // Print out all available subscriptions foreach (var sub in subscriptionResponse.Value) { Console.WriteLine($"Subscription Name: {sub.Name}"); Console.WriteLine($"Subscription ID: {sub.SubscriptionId}\n"); } } } }
Quick Notes
- If the authenticated identity has access to multiple subscriptions, this endpoint will return all of them. You can filter results by
Nameor other properties if you need a specific subscription. - Double-check that your access token includes the correct scope for the Azure Management API (usually
https://management.azure.com/.defaultwhen requesting the token initially).
内容的提问来源于stack exchange,提问作者Balaji

