【问题标题】:How to setup azure relay hybrid connections using C# to connect to on-premises SQL Server?如何使用 C# 设置 Azure 中继混合连接以连接到本地 SQL Server?
【发布时间】:2019-08-08 04:43:11
【问题描述】:

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

【问题讨论】:

    标签: c# azure azure-servicebusrelay azure-hybrid-connections


    【解决方案1】:

    您可以在这个问题中阅读为什么这不起作用:Connecting to an Hybrid connection served by the Hybrid connection manager

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      • 2022-06-13
      • 1970-01-01
      相关资源
      最近更新 更多