简体   繁体   English

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

[英]ASP.NET Core MVC MySQL Server Connection

I'm having issues trying to establish a connection to a server I've setup using Windows Server 2019 in ASP.NET Core MVC 3.1.我在尝试建立与在 ASP.NET Core MVC 3.1 中使用 Windows Server 2019 设置的服务器的连接时遇到问题。

The only things I've installed on the server is the MySQL suite and IIS.我在服务器上安装的唯一东西是 MySQL 套件和 IIS。 This server is also being hosted on my computer locally using VirtualBox and is setup using a Bridged Adapter.该服务器也使用 VirtualBox 在我的计算机上本地托管,并使用桥接适配器进行设置。

The ASP.NET Core MVC project was created using the default MVC option in Visual Studio. ASP.NET Core MVC 项目是使用 Visual Studio 中的默认 MVC 选项创建的。 No third-party services are included here.这里不包括第三方服务。

In ASP.NET Core, the connection string appears as follows:在 ASP.NET Core 中,连接字符串如下所示:

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

Upon running the project using the above Connection String, the following errors appear in my browser:使用上述连接字符串运行项目后,我的浏览器中出现以下错误:

Win32Exception: The system cannot find the file specified. Win32Exception: 系统找不到指定的文件。 Unknown location位置不明

SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. SqlException:建立与 SQL 服务器的连接时发生与网络相关或特定于实例的错误。 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.验证实例名称是否正确,并且 SQL 服务器配置为允许远程连接。 (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) (提供者:TCP 提供者,错误:0 - 连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立连接失败,因为连接的主机没有响应。) Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection (DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions userOptions, out DbConnectionInternal connection)

However, I cannot for the life of me figure out why this doesn't work.但是,我一生都无法弄清楚为什么这不起作用。 I've looked around the internet quite a bit but don't know enough about how ASP.NET interacts with a MySQL server, and whether or not I am using incorrect parameters.我已经在互联网上看了很多,但对 ASP.NET 如何与 MySQL 服务器交互以及我是否使用了不正确的参数知之甚少。 I've tried using additional parameters like Trusted_Connection=True/False;我尝试使用其他参数,例如Trusted_Connection=True/False; and MultipleActiveResultSets=True/False;MultipleActiveResultSets=True/False; in hopes to produce any different results, but still nothing (I specifically mention these two because they come by default).希望产生任何不同的结果,但仍然没有(我特别提到这两个,因为它们是默认出现的)。

To test whether the server was the culprit, I've replicated the connection string above using PHP v7 with PDO.为了测试服务器是否是罪魁祸首,我使用 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"];
}
?>

I can confirm that this PHP code works 100%.我可以确认这个 PHP 代码 100% 有效。

Additionally, I've also tested establishing a server connection using Azure MySQL and by using the generated Connection String that is created in Azure.此外,我还测试了使用 Azure MySQL 和使用在 Azure 中创建的生成的连接字符串建立服务器连接。 This also works 100%.这也100%有效。

This leads me to believe that my Windows Server is the culprit and that it could be related to one or more specific services being disabled/blocked.这让我相信我的 Windows 服务器是罪魁祸首,它可能与一项或多项特定服务被禁用/阻止有关。 But at the same time, if the PHP code could establish a connection and grab data, surely it can't be caused by the Connection String code??但同时,如果PHP代码可以建立连接并抓取数据,那肯定不会是连接字符串代码造成的吧??

I think the issue could be related to the logic in my Controller code.我认为这个问题可能与我的 Controller 代码中的逻辑有关。

If anyone could provide some insight, I would greatly appreciate it.如果有人能提供一些见解,我将不胜感激。 It could just be something super-duper simple.它可能只是超级简单的东西。

I'll leave this for anyone passing by.我会把这个留给路过的人。

Tl;dr: Code in 'Startup.cs' was the driven factor causing this issue, namely the section involved with adding a database context to the application. Tl; dr:“Startup.cs”中的代码是导致此问题的驱动因素,即涉及向应用程序添加数据库上下文的部分。 Also important to ensure Ubuntu server is not blocked by Firewall policies as well.确保 Ubuntu 服务器也不会被防火墙策略阻止也很重要。

Default method (using Microsoft SQL):默认方法(使用 Microsoft SQL):

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

Correct method (using Pomelo):正确方法(使用 Pomelo):

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

Notice the difference in ' .UseSqlServer() ' vs ' .UseMySql() '.请注意“ .UseSqlServer() ”与“ .UseMySql() ”的区别。 This was because in my Ubuntu server, it was setup with MySQL as the driver and NOT an MSSQL driver.这是因为在我的 Ubuntu 服务器中,它是使用 MySQL 作为驱动程序而不是 MSSQL 驱动程序设置的。 The effect of trying to use the "default method" was causing all kinds of issues in trying to establish a backend connection.尝试使用“默认方法”的效果是在尝试建立后端连接时导致各种问题。

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

Section below does not directly relate to the solution, but does provide insight as to how I troubleshooted this issue.下面的部分与解决方案没有直接关系,但确实提供了我如何解决此问题的见解。

To verify this, I also had to check other factors within the Ubuntu server itself.为了验证这一点,我还必须检查 Ubuntu 服务器本身的其他因素。 Namely, enabling Port 3306 through the Firewall, changing the " bind-address " parameter in the " mysql.cnf " file, and of course, checking the actual version the SQL driver itself that was being used.即通过防火墙启用端口 3306,更改“ mysql.cnf ”文件中的“ bind-address ”参数,当然还要检查正在使用的 SQL 驱动程序本身的实际版本。

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

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

Checking SQL driver version: https://phoenixnap.com/kb/how-to-check-mysql-version检查SQL驱动版本: https://phoenixnap.com/kb/how-to-check-mysql-version

Upon applying these changes (alongside using Pomelo's " .UseMySQL() " method), I ran my application and lo and behold, the page that involves using a database connection did not produce any errors.应用这些更改后(以及使用 Pomelo 的“ .UseMySQL() ”方法),我运行了我的应用程序,你瞧,涉及使用数据库连接的页面没有产生任何错误。 It simply required me to "Apply Migrations" as if I were working with a Local DB and have forgotten to update the database.它只是要求我“应用迁移”,就好像我正在使用本地数据库并且忘记更新数据库一样。

Since you're getting a SqlException , you must be trying to connect (to MySQL Server) with System.Data.SqlClient or Microsoft.Data.SqlClient .由于您收到SqlException ,因此您必须尝试使用System.Data.SqlClientMicrosoft.Data.SqlClient连接(到 MySQL 服务器)。 This isn't supported;不支持; those are only for Microsoft SQL Server.这些仅适用于 Microsoft SQL 服务器。

Install MySqlConnector and use the MySqlConnection class to establish a connection.安装MySqlConnector并使用MySqlConnection class 建立连接。 See https://mysqlconnector.net/connection-options/ for the full connection string reference, but the most simple connection string will be "Server=<server IP/host name>;Database=testdatabase;User ID=testuser;Password=testpassword;"有关完整的连接字符串参考,请参阅https://mysqlconnector.net/connection-options/ ,但最简单的连接字符串将是"Server=<server IP/host name>;Database=testdatabase;User ID=testuser;Password=testpassword;" . .

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

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