当我在azure docs post man上尝试azure rest api url时,我能够得到一个包含所有资源组的json。 https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/list#code-try-0 a link
但是我正在从ASP.NET MVC Core C#应用程序中尝试它,但收到的是空数组。
public async Task<ResourceGroupModel> GetResourceGroupStatus()
{
ResourceGroupModel resourceGroupModel = null;
try
{
string requestUrlString = iconfiguration.GetValue<string>("HealthSettings:AzureGetResourcesBySubscriptionURL");
string azureSubscription = iconfiguration.GetValue<string>("HealthSettings:AzureSubscription");
string clientId = iconfiguration.GetValue<string>("HealthSettings:ClientId");
string tenantId = iconfiguration.GetValue<string>("HealthSettings:TenantId");
string clientSecret = iconfiguration.GetValue<string>("HealthSettings:ClientSecret");
Uri requestUrl = new Uri(requestUrlString.Replace("{subscriptionId}", azureSubscription));
string token = await GetAccessToken(tenantId, clientId, clientSecret);
_httpClient.DefaultRequestHeaders.Remove("Authorization");
_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var response = _httpClient.GetAsync(requestUrl);
if (response.Result.IsSuccessStatusCode)
{
var data = response.Result.Content.ReadAsStringAsync();
resourceGroupModel = ResourceGroupModel.FromJson(data.Result.ToString());
}
}
catch (Exception ex)
{
}
return resourceGroupModel;
}
能否请您帮助我摆脱Azure REST API的奇怪行为。提前谢谢了。 :)
答案 0 :(得分:0)
您的服务主体无权访问资源组。
答案 1 :(得分:0)
正如Ciubotariu所说,您的服务负责人无权访问资源组。但是,如果仅将服务主体添加到资源组,则只能获取指定的资源组。因此,将您的服务主体添加到您的订阅中。步骤如下:
2。添加您的服务主体并为其分配角色,例如Contributor。
更新:
4。这是我使用的完整代码:
var appId = "xxxxxxxxxxxxxxx";
var secretKey = "xxxxxxxxxxxxxxxxxxxxx";
var tenantId = "xxxxxxxxxxxxxxxxx";
var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
ClientCredential clientCredential = new ClientCredential(appId, secretKey);
var tokenResponse = context.AcquireTokenAsync("https://management.azure.com/", clientCredential).Result;
var accessToken = tokenResponse.AccessToken;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var baseUrl = new Uri($"https://management.azure.com/");
var requestURl = baseUrl +
@"subscriptions/xxxxxxxxxxxxxxxx/resourcegroups?api-version=2019-05-01";
var response = client.GetAsync(requestURl).Result.Content.ReadAsStringAsync().Result;
}
答案 2 :(得分:0)
删除现有的clientsecret并创建一个新的servicesecret即可解决此问题。