.net 如何使用Azure.ResourceManager.CostManagement获取Azure订阅每日详细费用

fnvucqvd  于 2023-11-20  发布在  .NET
关注(0)|答案(1)|浏览(131)

我在互联网上广泛搜索,找不到一个Azure.ResourceManager.CostManagement .NET SDK的示例来显示如何获取成本。
我需要这个来获取每日Azure订阅的详细费用。

pkbketx9

pkbketx91#

  • 我尝试了下面的代码,并收到了如下成功输出:-*
using Microsoft.Rest.Azure.Authentication;
using Microsoft.Azure.Management.Consumption;
using Microsoft.Azure.Management.Consumption.Models;
using Microsoft.Rest.Azure;

class Program
{
    static async Task Main(string[] args)
    {
        string tenantId = "xxxxxx5";
        string clientId = "xxxxxx35cb";
        string clientSecret = "xxxxxx8dkdBH";
        string subscriptionId = "xxxxxxb2a7";

        var serviceClientCredentials = ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, clientSecret).Result;

        var consumptionManagementClient = new ConsumptionManagementClient(serviceClientCredentials)
        {
            SubscriptionId = subscriptionId
        };

        // Get the first and last day of the current month
        var firstDayOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
        var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);

        // Create a filter to get the usage details for the current month
        var filter = $"properties/usageStart ge '{firstDayOfMonth}' and properties/usageEnd le '{lastDayOfMonth}'";

        // Get the usage details for the current month
        var dailyCosts = new List<UsageDetail>();

        IPage<UsageDetail> usageDetails = await consumptionManagementClient.UsageDetails.ListAsync(filter: filter);

        dailyCosts.AddRange(usageDetails);

        foreach (var usageDetail in dailyCosts)
        {
            Console.WriteLine($"{usageDetail.UsageStart}: {usageDetail.PretaxCost}");
        }

        Console.WriteLine(dailyCosts.Sum(x => x.PretaxCost));
        Console.ReadLine();
        Console.WriteLine(
            $"Total cost for the current month: {dailyCosts.Sum(x => x.PretaxCost)}");
        Console.ReadLine();

字符串

输出:-

x1c 0d1x的数据

相关问题