我尝试测试此处提供的示例,以使用 Azure 混合连接连接到本地 SQL Server。我的服务器上安装了“混合连接管理器”,我可以通过 Azure App Service Plan 和 Azure Function 连接到数据库。
但是,我想使用来自另一台机器的相同混合连接,该机器使用 C# 代码驻留在不同的网络上。虽然我在该示例中将正确的连接字符串放在“PortBridgeClientAgent”程序中,但应用程序无法连接到本地 SQL 服务器。在 Azure 之外建立这种连接的正确方法是什么?
这是我的代码:
using Microsoft.Azure.Relay;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace TestConsoleApp
{
public static class Program
{
private const string RelayNamespace = "{NameSpace}.servicebus.windows.net";
private const string ConnectionName = "{ConnectionName}";
private const string KeyName = "RootManageSharedAccessKey";
private const string Key = "{Key}";
public static void Main() => RunAsync().GetAwaiter().GetResult();
private static async Task RunAsync()
{
var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
var client = new HybridConnectionClient(new Uri($"sb://{RelayNamespace}/{ConnectionName}"), tokenProvider);
var hybridConnectionStream = await client.CreateConnectionAsync();
var connectionStringBuilder = new SqlConnectionStringBuilder
{
DataSource = "{SqlServerHostName},1433",
InitialCatalog = "{DatabaseName}",
IntegratedSecurity = false,
UserID = "{SqlLogin}",
Password = "{Password}",
};
try
{
using (var connection = new SqlConnection(connectionStringBuilder.ToString()))
{
connection.Open();
var command1 = new SqlCommand("Query", connection);
using (var dataReader = await command1.ExecuteReaderAsync())
{
var result = dataReader;
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
}
Console.ReadLine();
await hybridConnectionStream.CloseAsync(CancellationToken.None);
}
}
}