调用Azure Monitoring REST API上报自定义指标报错排查咨询
错误原因
你遇到的报错本质是DNS解析失败,核心有以下几个配置错误:
- 终结点配置错误
Azure自定义指标上传没有全局统一的https://monitoring.azure.com服务地址,必须使用你目标资源所在区域的专属终结点,格式为https://<区域标识>.monitoring.azure.com,比如资源部署在东亚区就用https://eastasia.monitoring.azure.com。 - 资源参数为空
CreateAsync方法传入的资源组、资源提供程序命名空间、资源类型、资源名称四个参数不能留空,必须填写你要上报指标的目标Azure资源的对应属性,否则构造的请求URI不合法。 - 认证Scope格式错误
代码里配置的Scope多了一个斜杠,https://monitoring.azure.com//.default要修改为https://monitoring.azure.com/.default。 - 请求负载未正确序列化
你当前写死了请求内容为测试字符串,正式上报需要将构造的Metric对象序列化为JSON格式后作为请求内容传入。 - 权限配置缺失
你使用的服务主体(即ClientSecretCredential对应的Azure AD应用注册)需要提前被授予目标资源的Monitoring Metrics Publisher角色,否则后续认证通过后也会报权限不足错误。
修复后的核心代码参考
// 1. 替换为你资源所在区域的终结点 var monitorClient = new MonitorClient( subscriptionId: "你的订阅ID", endpoint: new Uri("https://<你的资源所在区域>.monitoring.azure.com"), credential); // 2. 填写真实的资源参数 await monitorClient.CreateAsync( resourceGroupName: "你的资源组名称", resourceProviderNamespace: "目标资源的提供程序命名空间,比如虚拟机就是Microsoft.Compute", resourceType: "目标资源类型,比如虚拟机就是virtualMachines", resourceName: "目标资源名称", new { }); // 3. 修复Scope _pipeline = HttpPipelineBuilder.Build( options, new BearerTokenAuthenticationPolicy(tokenCredential, "https://monitoring.azure.com/.default")); // 4. 序列化Metric对象为请求内容 request.Content = RequestContent.Create( JsonSerializer.SerializeToUtf8Bytes(parameters2));
内容的提问来源于stack exchange,提问作者Luis Valencia
相关产品推荐
相关产品推荐

