我尝试测试提供的示例here,以使用Azure混合连接连接到本地SQL Server。我的服务器上安装了“混合连接管理器”,我可以通过Azure应用服务计划和Azure功能连接到数据库。
但是,我想使用C#代码从另一台计算机使用的同一混合连接驻留在不同的网络上。在该示例中,尽管我在“ PortBridgeClientAgent”程序中输入了正确的连接字符串,但该应用程序无法连接到本地SQL Server。在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);
}
}
}
答案 0 :(得分:2)
您可以阅读以下原因无法解决此问题:Connecting to an Hybrid connection served by the Hybrid connection manager
除了连接到Service Bus和请求SQL连接之外,应用程序服务中还有许多其他活动。这意味着目前无法使用它来建立从外部App Services到本地服务器的连接。