繁体   English   中英

我如何连接到我通常使用 .net6 应用程序通过 GlobalProtect 连接到的 Microsoft SQL Server 数据库

[英]How do i connect to a Microsoft SQL Server database to which i normally connect via GlobalProtect using .net6 application

我在我的 Azure Function 应用程序中使用 .net6、Azure Function 版本 4 和 SqlClient。

我有这样的连接字符串

Server=tcp:name.database.windows.net,1433;Initial Catalog=dbName;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=120;

通常,我通过提供门户、用户名和密码使用 GlobalProtect 访问此数据库。 现在,我正在开发一个将访问此数据库的 Azure Function 应用程序,但出现此错误

System.Private.CoreLib:执行函数时出现异常:MyAzurefunction。 Core.Net SqlClient 数据提供程序:无法打开登录请求的服务器“serverName”。 不允许 IP 地址为“MyIpAddress”的客户端访问服务器。 要启用访问,请使用 Windows Azure 管理门户或在 master 数据库上运行 sp_set_firewall_rule 以为此 IP 地址或地址范围创建防火墙规则。 此更改最多可能需要五分钟才能生效。

我知道我收到此错误是因为我的 IpAddress 无法访问服务器,但我如何通过我的连接字符串连接到它?

我创建了 azure SQL 数据库。 数据库连接字符串:

Server=tcp:<serverName>.database.windows.net,1433;Initial Catalog=<database Name>;Persist Security Info=False;User ID=server;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30; 

图片供参考:

在此处输入图像描述

我在 Visual Studio 中使用 .net 6 创建了函数应用程序。 图片供参考:

在此处输入图像描述

在此处输入图像描述

我将它发布到 Azure。 图片供参考:

在此处输入图像描述

在发布的页面上选择椭圆(...)并选择Manage Azure App Service settings 图片供参考:

在此处输入图像描述

单击“应用程序”页面中的“添加设置”并添加设置名称。 图片供参考:

在此处输入图像描述

在 sql_connection 中,在远程部分的本地部分中输入 sql db 的连接字符串,单击从本地插入值。 图片供参考:

在此处输入图像描述

在项目的管理 Nuget 包中安装 System.Data.SqlClient 包。 我添加了以下连接到 SQL 数据库的代码:

using System.Data.SqlClient;
using System.Threading.Tasks;

[FunctionName("DatabaseCleanup")]
public static async Task Run([TimerTrigger("*/15 * * * * *")]TimerInfo myTimer, ILogger log)
{
    // Get the connection string from app settings and use it to create a connection.
    var str = Environment.GetEnvironmentVariable("sqldb_connection");
    using (SqlConnection conn = new SqlConnection(str))
    {
        conn.Open();
        var text = "UPDATE SalesLT.SalesOrderHeader " +
                "SET [Status] = 5  WHERE ShipDate < GetDate();";

        using (SqlCommand cmd = new SqlCommand(text, conn))
        {
            // Execute the command and log the # rows affected.
            var rows = await cmd.ExecuteNonQueryAsync();
            log.LogInformation($"{rows} rows were updated");
        }
    }
}

以上函数每 15 秒运行一次,以根据发货日期更新Status列。

我在数据库防火墙设置中添加了我的 IP 地址。 图片供参考:

在此处输入图像描述

启动后 15 秒,函数运行。 SalesOrderHeader 表中更新行数的输出:

在此处输入图像描述

通过这种方式,我将 SQL 数据库连接到我的函数应用程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM