Azure“配置文件-按资源组列出”rest API return {“value”:[]}

zpf6vheq  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(97)

我想获取资源组下的配置文件列表(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 "";
}

谁知道怎么解决?
谢谢你,谢谢

mnowg1ta

mnowg1ta1#

从**Try it页面运行REST API调用时,查询基于登录**(委托)用户角色。

我在**Try it页面查询REST API得到下面的response**:

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

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

当我运行下面修改后的代码时,使用Try it页面中相同的参数,它生成了token作为服务主体,并返回了**相同的 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);
        }
    }
}

回复:

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

相关问题