PAYATHON 2026

Azure Billing API 在 C# 中返回 404 错误

数据小陈

结论

出现 404,主要是因为请求仍在使用旧版 API:

api-version=2015-06-01-preview

示例代码的注释要求使用的版本是:

api-version=2016-05-01-preview

成功获取 Azure AD token 只能说明身份验证已经通过,不能证明资源路径和 API 版本有效。请先更新 URL 中的 api-version,然后重新发送请求。

修正请求代码

测试时可以缩短查询的时间范围,以排除日期范围或订阅数据可用性造成的干扰:

string requestURL = String.Format(
    "{0}/subscriptions/{1}/providers/Microsoft.Commerce/UsageAggregates" +
    "?api-version=2016-05-01-preview" +
    "&reportedStartTime=2016-12-01T00%3A00%3A00%2B00%3A00" +
    "&reportedEndTime=2016-12-02T00%3A00%3A00%2B00%3A00" +
    "&aggregationGranularity=Hourly" +
    "&showDetails=true",
    ConfigurationManager.AppSettings["ARMBillingServiceURL"],
    ConfigurationManager.AppSettings["SubscriptionID"]);

对应的请求地址类似于:

https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Commerce/UsageAggregates?api-version=2016-05-01-preview&reportedStartTime=2016-12-01T00%3A00%3A00%2B00%3A00&reportedEndTime=2016-12-02T00%3A00%3A00%2B00%3A00&aggregationGranularity=Hourly&showDetails=true

还需要检查的配置

确认 SubscriptionID 填写的是完整的 Azure 订阅 GUID,而不是租户 ID、应用程序 ID 或其他标识:

<add key="SubscriptionID"
     value="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" />

当前登录用户还需要至少拥有该订阅的以下角色之一:

  • Owner
  • Contributor
  • Reader

权限不足通常会返回 401 或 403,而不是这里的 404。

配置键名最好和代码保持一致。例如,代码读取的是:

ConfigurationManager.AppSettings["ClientID"]

配置中也建议写成:

<add key="ClientID" value="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" />

常见的 .NET Framework 配置实现通常不区分键名大小写,但统一写法可以避免迁移或更换配置读取方式后出现问题。

注意旧接口已经过时

Microsoft.Commerce/UsageAggregates 及上述 preview API 版本都属于旧版 Azure Billing API。将版本改为 2016-05-01-preview,只是针对这个历史示例的修正方法。

如果在当前 Azure 环境中调用,即使版本已经修改,也可能因旧接口停用或订阅类型不受支持而报错。新项目不应继续依赖这个 GitHub 示例,应改用 Azure Cost Management/Consumption API,例如:

POST https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.CostManagement/query?api-version={supported-api-version}

具体的 api-version 应以调用时 Azure 官方文档列出的受支持版本为准,不能直接沿用旧接口的版本号。

建议按以下顺序排查:

  1. 将旧示例中的 2015-06-01-preview 改为 2016-05-01-preview。
  2. 确认 SubscriptionID 是正确的订阅 GUID。
  3. 使用较短且有效的时间范围测试。
  4. 确认登录用户拥有该订阅的读取权限。
  5. 如果当前环境仍返回 404,请迁移到 Azure Cost Management API,不要再继续尝试已经过时的 UsageAggregates 端点。

备注:内容仅供参考。