繁体   English   中英

AZURE 得到虚拟机 ip SDK c#

[英]AZURE get ip of virtual machine SDK c#

我正在尝试获取虚拟机的主要 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
}

感谢帮助

试试这个代码:

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);
            }
        }

    }
}

这是我在本地测试的结果: 在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM