Azure“配置文件 - 按资源组列出”rest api 返回 {"value":[]}

问题描述 投票:0回答:1

我想使用 azure rest api

获取资源组下的配置文件列表

我可以通过页面上的“尝试一下”得到正确的回复:

但是当我通过具有相同参数的代码请求它时,我只得到 '{"value":[]}'。代码是:

string url = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles?api-version=2023-05-01";
using HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
try
{
    HttpResponseMessage response = await httpClient.GetAsync(url);

    if (response.IsSuccessStatusCode)
    {
        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }
    else
    {
        string errorContent = await response.Content.ReadAsStringAsync();
        _logger.Info("Request failed: {0}, {1}", response.StatusCode, errorContent);
        return "";
    }
}
catch (Exception ex)
{
    _logger.Error($"{ex.Message}: {ex.StackTrace}");
    return "";
}

谁知道如何解决?

谢谢!

azure rest cdn
1个回答
0
投票

当您从

Try it
页面运行 REST API 调用时,查询将基于 登录(委派)用户角色进行工作。

enter image description here

当我从 Try it

 页面运行 REST API 查询时,我得到了以下 
响应

GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles?api-version=2023-05-01

enter image description here

为了通过在代码中运行请求来获得相同的结果,我创建了一个应用程序并在订阅下分配了Reader角色,如下所示:

enter image description here

当我使用

Try it
页面中的相同参数运行下面的修改后的代码时,它生成令牌作为服务主体并返回 same API 响应,如下所示:

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Identity.Client;

class Program
{
    static async Task Main()
    {
        // Create the confidential client application object
        IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
            .Create("appId")
            .WithClientSecret("secret")
            .WithAuthority(new Uri("https://login.microsoftonline.com/tenantId"))
            .Build();

        // Get the access token
        string[] scopes = new string[] { "https://management.azure.com/.default" };
        AuthenticationResult authResult = await confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync();

        // Print the access token
        Console.WriteLine("Access token: {0}\n", authResult.AccessToken);

        // Call Management API using the access token
        await CallManagementApi(authResult.AccessToken);
    }

    static async Task CallManagementApi(string accessToken)
    {
        try
        {           
            using (var httpClient = new HttpClient())
            {
                var subscriptionId = "subId";
                var resourceGroupName = "rgname"; // Replace with resource group name
                var endpointUrl = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles?api-version=2023-05-01";

                // Set the required headers
                httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
                httpClient.DefaultRequestHeaders.Add("Accept", "application/json");

                var response = await httpClient.GetAsync(endpointUrl);
                response.EnsureSuccessStatusCode();

                var result = await response.Content.ReadAsStringAsync();
                // Process the API response as needed
                Console.WriteLine("\nAPI Response:\n" + result);
            }
        }
        catch (HttpRequestException ex)
        {
            // Handle or log the exception
            Console.WriteLine("Error calling API: " + ex.Message);
        }
    }
}

回复:

enter image description here

在您的情况下,请检查您如何在代码中使用正确的 RBAC 角色生成 访问令牌,并确保从 Try it 页面为 订阅 Id资源组 参数传递

相同的值

© www.soinside.com 2019 - 2024. All rights reserved.