ASP.NET 核心 MVC MySQL 服务器连接

ASP.NET Core MVC MySQL Server Connection

我在尝试建立与我在 ASP.NET Core MVC 3.1 中使用 Windows Server 2019 设置的服务器的连接时遇到问题。

我在服务器上安装的唯一东西是 MySQL 套件和 IIS。该服务器也使用 VirtualBox 在我的本地计算机上托管,并使用桥接适配器进行设置。

ASP.NET 核心 MVC 项目是使用 Visual Studio 中的默认 MVC 选项创建的。此处不包括第三方服务。

在ASP.NETCore中,连接字符串出现如下:

"ConnectionStrings": {
     "ApplicationContext": "Server=<server IP/host name>;Initial Catalog=testdatabase;User ID=testuser;Password=testpassword;"
}

在运行使用上述连接字符串的项目后,我的浏览器出现以下错误:

Win32Exception: The system cannot find the file specified. Unknown location

SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.) Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions userOptions, out DbConnectionInternal connection)

但是,我终其一生都无法弄清楚为什么这不起作用。我在互联网上浏览了很多,但对 ASP.NET 如何与 MySQL 服务器交互以及我是否使用了不正确的参数知之甚少。我试过使用其他参数,例如 Trusted_Connection=True/False;MultipleActiveResultSets=True/False; 希望产生任何不同的结果,但仍然没有(我特别提到这两个,因为它们默认出现)。

为了测试服务器是否是罪魁祸首,我使用 PHP v7 和 PDO 复制了上面的连接字符串。

<?php
$server = "<server IP/host name>";
$port = 3306;
$db = "testdatabase";
$username = "testuser";
$password = "testpassword";

try {
    $conn = new PDO("mysql:host=$server;port=$port;dbname=$db", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected";
} catch (PDOException $err) {
    echo $err;
}

if ($conn) {
    $query = "SELECT * FROM testTable";
    $result = $conn->query($query);
} else {
    echo "Query failed";
}

foreach ($entity as $result) {
    echo "<br />" . $result["Id"];
}
?>

我可以确认此 PHP 代码 100% 有效。

此外,我还测试了使用 Azure MySQL 和使用在 Azure 中创建的生成的连接字符串建立服务器连接。这也 100% 有效。

这让我相信我的 Windows 服务器是罪魁祸首,它可能与一项或多项特定服务有关 disabled/blocked。但是同时,如果PHP代码能够建立连接并抓取数据,那肯定不会是Connection String代码造成的吧??

我认为这个问题可能与我的控制器代码中的逻辑有关。

如果有人能提供一些见解,我将不胜感激。它可能只是超级简单的东西。

由于您获得 SqlException,您必须尝试连接(到 MySQL 服务器)与 System.Data.SqlClientMicrosoft.Data.SqlClient。这不受支持;这些仅适用于 Microsoft SQL 服务器。

安装 MySqlConnector and use the MySqlConnection class to establish a connection. See https://mysqlconnector.net/connection-options/ 以获得完整的连接字符串参考,但最简单的连接字符串将是 "Server=<server IP/host name>;Database=testdatabase;User ID=testuser;Password=testpassword;"

我会把这个留给路过的人。

Tl;dr:'Startup.cs' 中的代码是导致此问题的驱动因素,即涉及向应用程序添加数据库上下文的部分。同样重要的是要确保 Ubuntu 服务器也不会被防火墙策略阻止。

默认方法(使用 Microsoft SQL):

services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DataContext")));

正确方法(使用Pomelo):

services.AddDbContext<DataContext>(options => options.UseMySql(Configuration.GetConnectionString("DataContext")));

请注意“.UseSqlServer()”与“.UseMySql()”的区别。这是因为在我的 Ubuntu 服务器中,它是使用 MySQL 作为驱动程序而不是 MSSQL 驱动程序设置的。尝试使用“默认方法”的结果是在尝试建立后端连接时导致各种问题。

安装参考:https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql

以下部分与解决方案没有直接关系,但确实提供了有关我如何解决此问题的见解。

为了验证这一点,我还必须检查 Ubuntu 服务器本身的其他因素。即,通过防火墙启用端口 3306,更改“mysql.cnf”文件中的“bind-address”参数,当然,还要检查正在使用的 SQL 驱动程序本身的实际版本.

启用端口 3306:https://www.digitalocean.com/community/tutorials/how-to-allow-remote-access-to-mysql

更改“绑定地址”参数:https://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html

正在检查 SQL 驱动程序版本:https://phoenixnap.com/kb/how-to-check-mysql-version

应用这些更改后(连同使用 Pomelo 的“.UseMySQL()”方法),我 运行 我的应用程序,你瞧,涉及使用数据库连接的页面没有产生任何错误。它只是要求我“应用迁移”,就好像我正在使用本地数据库并且忘记更新数据库一样。