[英]Consuming Azure REST API in C# application shows no response
當我在azure docs post man上嘗試azure rest api url時,我能夠得到一個擁有所有資源組的json。 https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/list#code-try-0 一個鏈接
但我從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的奇怪行為嗎? 提前謝謝了。 :)
您的服務主體無權訪問資源組。
正如Ciubotariu所說,您的服務主體無權訪問資源組。 但是,如果僅將服務主體添加到資源組,則只能獲取指定的資源組。 因此, 請將您的服務主體添加到您的訂閱中 。 以下是步驟:
1.轉到您的訂閱,單擊“訪問控制”>“添加”(添加角色分配)
2.添加您的服務主體並為其分配角色,如Contributor。
更新:
這是我使用的完整代碼:
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;
}
刪除現有的clientsecret並為服務原則創建新的clientsecret解決了這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.