0

我尝试测试此处提供的示例,以使用 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);
        }
    }
}
4

1 回答 1

2

您可以在这个问题中阅读为什么这不起作用:连接到由混合连接管理器提供的混合连接

除了连接到服务总线和请求 SQL 连接之外,应用程序服务中还有更多工作要做。这意味着目前无法使用它来创建从外部应用服务到您的本地服务器的连接。

于 2019-03-18T16:32:14.227 回答