每当var response
行执行时,它都会抛出一个异常,指出
操作返回了无效的状态代码“BadRequest”
我在 Azure Resource Graph Explorer 中执行的相同请求按预期工作。但是出于某种奇怪的原因,当我在运行 .net 6 框架的 .net 控制台应用程序中执行此操作时,它告诉我这是一个错误的请求,而实际上它是正确的请求。但是,在显示该错误后,它说Principal used: IsAuthenticated:True Type:User TenantId: xxxxx UserPrincipalName: xxxx
安装的软件包:
<PackageReference Include="Microsoft.Azure.Management.ResourceGraph" Version="2.1.0" />
<PackageReference Include="Microsoft.Azure.Services.AppAuthentication" Version="1.6.2" />
程序.cs
using Microsoft.Azure.Management.ResourceGraph;
using Microsoft.Azure.Management.ResourceGraph.Models;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Rest;
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
RunResourceGraphQuery(azureServiceTokenProvider).Wait();
if (azureServiceTokenProvider.PrincipalUsed != null)
{
Console.WriteLine($"{Environment.NewLine}Principal used: {azureServiceTokenProvider.PrincipalUsed}");
}
Console.ReadLine();
static async Task RunResourceGraphQuery(AzureServiceTokenProvider azureServiceTokenProvider)
{
Console.WriteLine($"{Environment.NewLine}{Environment.NewLine}Please enter the subscription Id");
var subscriptionId = Console.ReadLine();
List<string> subscriptions = new();
subscriptions.Add(subscriptionId);
try
{
var tokenCredentials = new TokenCredentials(await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/").ConfigureAwait(false));
var resourceGraphClient = new ResourceGraphClient(tokenCredentials);
var userQueryRequest = new QueryRequest(subscriptions: subscriptions, query: "resources | project name, ['type'] | limit 5", null, null);
var response = resourceGraphClient.Resources(userQueryRequest);
Console.WriteLine(response);
}
catch (Exception exp)
{
Console.WriteLine($"Error message: {exp.Message}");
}
}