【问题标题】:AZURE get ip of virtual machine SDK c#AZURE获取虚拟机SDK c#的ip
【发布时间】:2023-03-02 22:21:01
【问题描述】:

我正在尝试获取虚拟机的主 IP,但出现错误 'virtualMachine.GetPrimaryPublicIPAddress().IPAddress' threw an exception of type 'System.NullReferenceException'

我在 Postman 中使用 Rest-API 成功获取了 IP 例如 Postman GET 方法

https://management.azure.com/subscriptions/{{subid}}/resourceGroups/{{rg}}/providers/Microsoft.Network/networkInterfaces/{{vm_name}}?api-version=2020-11-01

我在 .Net 中的代码

var credentials = SdkContext.AzureCredentialsFactory
    .FromServicePrincipal(clientId,
        clientSecret,
        tenantId,
        AzureEnvironment.AzureGlobalCloud);

var azure = Azure
    .Configure()
    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
    .Authenticate(credentials)
    .WithSubscription(subscriptionId);

foreach (var virtualMachine in azure.VirtualMachines.ListByResourceGroup(resourceGroupName))
{
    var name = virtualMachine.Name; 
    var os_type = virtualMachine.OSType; 
    var size = virtualMachine.OSDiskSize;
    var ip = virtualMachine.GetPrimaryPublicIPAddress().IPAddress; //Error
}

感谢您的帮助

【问题讨论】:

  • 你解决了吗?您介意接受我的回答供其他人参考吗?

标签: c# azure azure-virtual-machine


【解决方案1】:

试试这个代码:

using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using System;
using System.Threading.Tasks;

namespace myVMDotnetProject
{
    class Program
    {
        static void Main(string[] args)
        {
            GetVMInfo();

            Console.WriteLine("okok");
            Console.ReadLine();
        }


        static async Task  GetVMInfo()
        {
            var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION", EnvironmentVariableTarget.User));

            var azure = Azure
                .Configure()
                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                .Authenticate(credentials)
                .WithDefaultSubscription();

            IVirtualMachines _client = azure.VirtualMachines;
            var list = await _client.ListAsync();

            foreach (var instance in list)
            {
                var name = instance.Name;
                var ip = instance.GetPrimaryPublicIPAddress().IPAddress;
                Console.WriteLine("name: " + name + ", ip: " + ip);
            }
        }

    }
}

这是我在本地测试的结果:

【讨论】:

  • 当我试图使函数异步时,程序停止工作,其余部分到达等待 _client.ListAsync();不写错误感谢帮助
猜你喜欢
  • 2019-10-20
  • 1970-01-01
  • 2012-08-04
  • 1970-01-01
  • 2017-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-01
相关资源
最近更新 更多