如何用C#获取Azure服务列表?及Azure.Configure报错解决
问题解决与实现方案
错误原因与修复
你遇到的The type or namespace Configure does not exists in the namespace Azure错误,主要有两个核心原因及对应修复方式:
命名空间未正确引用
确保代码文件顶部添加以下命名空间:using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core;Fluent SDK版本差异
较新版本的Microsoft.Azure.Management.Fluent已移除Azure.Configure()入口,直接使用Azure.Authenticate()即可完成客户端初始化。修改后的初始化代码如下:string clientId = "your_client_id"; string clientSecret = "your_client_secret"; string tenantId = "your_tenant_id"; string subscriptionId = "your_subscription_id"; var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal( clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud); var azure = Azure.Authenticate(credentials).WithSubscription(subscriptionId);
获取Azure应用服务列表(Fluent SDK方案)
初始化完成后,可通过以下代码获取所有Web应用(应用服务)的列表:
// 获取订阅下所有Web应用 var webApps = azure.AppServices.WebApps.List(); foreach (var app in webApps) { // 输出应用核心信息 Console.WriteLine($"应用名称: {app.Name}, 资源组: {app.ResourceGroupName}, 运行状态: {app.State}"); }
推荐方案:使用Azure Resource Manager新SDK
由于Microsoft.Azure.Management.Fluent已进入维护模式,微软官方推荐使用Azure Resource Manager (ARM) 新SDK,实现步骤如下:
安装所需NuGet包:
Azure.ResourceManager.AppServiceAzure.Identity
实现代码:
using Azure.Identity; using Azure.ResourceManager; using Azure.ResourceManager.AppService; string clientId = "your_client_id"; string clientSecret = "your_client_secret"; string tenantId = "your_tenant_id"; string subscriptionId = "your_subscription_id"; // 初始化ARM客户端 var armClient = new ArmClient(new ClientSecretCredential(tenantId, clientId, clientSecret)); // 获取指定订阅资源 var subscription = await armClient.GetSubscriptionResource( new ResourceIdentifier($"/subscriptions/{subscriptionId}")).GetAsync(); // 遍历订阅下所有Web应用 await foreach (var webApp in subscription.GetWebAppsAsync()) { Console.WriteLine($"应用名称: {webApp.Data.Name}, 资源组: {webApp.Data.ResourceGroupName}, 默认域名: {webApp.Data.DefaultHostName}"); }
内容的提问来源于stack exchange,提问作者Traci
相关产品推荐
相关产品推荐

