无法从 ASP.NET 网络应用程序连接到我的 SQL Server Express

Can't connect to my SQL Server Express from an ASP.NET web app

我正在开发一个使用 SQL 服务器作为数据库的工具。

首先我使用的是 Visual Studio 的 localdb,然后我使用的是 Azure SQL 服务器,两者都运行良好。

我现在尝试托管我自己的 SQL Server Express,但我似乎无法连接到它。它托管在 Azure VM 中,我重新启动了它,启用了 TCP,并且我在 Azure 中打开了端口 1433。

我已经尝试过远程连接,运行 我本地计算机上的网络应用程序和连接到 tcp:{IP}\InstanceName,以及 运行 我的 IIS 服务器上的应用程序VM 在连接字符串中使用 .\InstanceName(尽管我仍然被告知要检查服务器是否设置正确以处理 TCP?)

在 VM 上本地连接,使用 Microsoft SQL Server Management Studio 可以,所以我怀疑 web.config 中的连接字符串一定是错误的...

看起来像这样:

<connectionStrings>
    <add name="defaultConnection" 
         connectionString="Server=tcp:12.345.678.910\InstanceName,1433;Initial Catalog=master;Persist Security Info=False;User ID=sa;Password={mypassword};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" 
         providerName="System.Data.SqlClient" />
</connectionStrings>

我收到的错误信息是:

Server Error in '/application-name' Application. The remote computer refused the network connection.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: The remote computer refused the network connection

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: [Win32Exception (0x80004005): The remote computer refused the network connection]

[SqlException (0x80131904): 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 - The remote computer refused the network connection.)]

(还有更多,但似乎并不重要 - 如果需要或有帮助,将 post)

知道我做错了什么吗?

SQL 服务器 Express 默认不允许远程连接。

您需要显式启用 远程连接 - 最简单的方法是使用 SQL Server Management Studio,连接到它,然后在 "Object Explorer" 对-单击服务器图标,然后选择 "Properties".

在出现的对话框中,确保 勾选 "Allow remote connections to this server" 复选框:

我自己找到了解决方案:

仅在服务器配置管理器中启用 TCP 是不够的,您还必须 SQL 服务器网络配置 > X 的协议 > TCP > 属性 > IP 地址并将 IPAll 下的 TCP 端口设置为 1433。