无法将 Azure WebJob 连接到 Azure VM 上的 SQL 数据库

Unable to connect an Azure WebJob to SQL database on Azure VM

我正在尝试连接到托管在 Azure 上的虚拟机中的 SQL 数据库。

我的应用服务和虚拟机在不同的订阅中。我有一个 VM 的 DNS 名称,它也有一个 public IP。我在 Azure VM 防火墙中添加了一条防火墙规则,为应用服务 IP 启用了 1433 端口(在属性-->其他出站 IP 地址中找到)。

在同一条规则中,我添加了我的 IP(目的是检查规则是否正确应用)并且我能够从我的 PC 使用 SSMS 连接到数据库。

我尝试在 App Service 上发布一个非常简单的 WebJob,只是为了尝试连接。这是我正在使用的代码:

static void Main(string[] args)
        {
            using (SqlConnection connection = new SqlConnection("Server=myvirtualmachine.westeurope.cloudapp.azure.com;Database=mydatabase;User ID=myuser;Password=mypassword;MultipleActiveResultSets=False;Connection Timeout=60;TrustServerCertificate=False;Persist Security Info=False"))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand("SELECT * FROM myTable", connection))
                {
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                Console.WriteLine(reader.GetValue(i));
                            }
                            Console.WriteLine();
                        }
                    }
                }
            }
        }

如果我 运行 这个 WebJob 我收到错误:

A network-related or instance-specific error occurred while establishing a connection to SQL Server.

是否必须使用 VNET 或混合连接才能将 Azure 应用服务连接到 Azure 虚拟机上的 SQL 数据库,或者是否可以通过其他方式实现?

是的,您需要使用 VNET 或启用 Public IP 才能从您的 SQL 虚拟机中的 Appservice 建立连接。

你阅读更多here