将 Azure 资源图与 .net SDK 结合使用

Using Azure resource graph with .net SDK

我正在尝试使用 Azure Resource Graph 和 Azure .NET SDK 查询我的 Azure 资源管理器资源。目前我一直在创建 ResourceGraphClient,我不太确定要为 System.Net.Http.DelegatingHandler[] 参数提供什么值。

根据我的研究,如果你想直接用System.Net.Http.DelegatingHandler[]创建ResourceGraphClient,这是不可能的。因为它是一个 projected 构造函数。更多详情请参考here

此外,根据我的测试,我们可以创建一个ResourceGraphClientServiceClientCredentialsclass。

例如 1. Create a service principal

az ad sp create-for-rbac -n "MyApp" --role contributor --sdk-auth
  1. 代码
public  async static Task Test() {


            CustomLoginCredentials creds = new CustomLoginCredentials();

            var resourceGraphClient = new ResourceGraphClient(creds);

            var queryReq = new QueryRequest {

                Subscriptions = new List<string> { "<your subscription id>" },
                Query = "where type == 'microsoft.web/sites'"

            };
            var result = await resourceGraphClient.ResourcesAsync(queryReq);
            Console.WriteLine(result.Count);
        }

class CustomLoginCredentials : ServiceClientCredentials {
        private static string tenantId = "<your sp tenant id>";
        private static string clientId = "your sp app id";
        private static string cert = "your sp password";
        private string AuthenticationToken { get; set; }
        public override void InitializeServiceClient<T>(ServiceClient<T> client)
        {
            var authenticationContext =
                new AuthenticationContext("https://login.windows.net/"+tenantId);
            var credential = new ClientCredential(clientId: clientId, clientSecret: cert);

            var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/",
                clientCredential: credential).Result;

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            AuthenticationToken = result.AccessToken;
        }
        public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (AuthenticationToken == null)
            {
                throw new InvalidOperationException("Token Provider Cannot Be Null");
            }



            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken);



            await base.ProcessHttpRequestAsync(request, cancellationToken);

        }