You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过.NET库运行AZ CLI命令?如何用C#/.NET 6获取AKS令牌?

问题解答

1. 是否可以通过某款.NET库运行AZ CLI命令?

可以实现,有两种常见方案:

  • 直接调用AZ CLI进程:用.NET自带的System.Diagnostics.Process类执行AZ CLI命令,适合需要复用现有CLI脚本逻辑的场景。
  • 使用Azure .NET SDK替代:微软官方提供了Azure.ResourceManager系列等Azure .NET SDK,可直接通过API完成AZ CLI的大部分操作,比调用进程更可靠、更易集成到业务逻辑中。

直接调用AZ CLI的示例代码

using System.Diagnostics;

var processStartInfo = new ProcessStartInfo
{
    FileName = "az",
    Arguments = "account show",
    RedirectStandardOutput = true,
    UseShellExecute = false,
    CreateNoWindow = true
};

using var process = Process.Start(processStartInfo);
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();

Console.WriteLine(output);

2. 是否可以使用Azure凭据,通过C#/.NET 6以编程方式获取Azure AKS服务器的令牌?

完全可以,无需依赖az aks get-credentials命令,直接通过Azure Identity SDK即可获取与kube/config中同款的令牌。

示例代码(.NET 6)

首先安装NuGet包:Azure.Identity

using Azure.Identity;

// AKS的固定受众URL,也可替换为集群的资源ID
var aksAudience = "https://aks.azure.com";
var credential = new DefaultAzureCredential();

// 请求针对AKS的访问令牌
var tokenRequestContext = new Azure.Core.TokenRequestContext(new[] { aksAudience });
var tokenResult = await credential.GetTokenAsync(tokenRequestContext);

// 输出的令牌即为kube/config中的token字段值
Console.WriteLine($"AKS访问令牌:{tokenResult.Token}");

说明

  • DefaultAzureCredential会自动从环境变量、Azure CLI缓存、托管标识等多种渠道获取有效凭据,适配本地开发和生产部署场景。
  • 获取到的令牌与az aks get-credentials生成的令牌完全一致,都是Azure AD颁发的用于访问AKS API服务器的有效凭证。

内容的提问来源于stack exchange,提问作者Kotletmeknow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 20:05:42