我有一个 .NET Core 应用程序作为 API。我可以将其连接到本地 SQL Server 数据库,但不能连接到网络上的其他数据库。
当我尝试使用 dbContext
访问远程数据库时,出现以下错误:
System.Data.SqlClient.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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
appsettings.json
对于本地:
"ConnectionStrings": {
"DefaultConnection": "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=ib;Integrated Security=True;"
}
appsettings.json
用于远程:
"ConnectionStrings": {
"DefaultConnection": "Server=[servername]\[instanz];Database=IBCore_Lange;User Id=sa;password=XXX"
}
我可以通过 SQL Server Management Studio 或系统的早期 (ASP.NET) 版本访问数据库。在Core中,我只能访问本地数据库。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
services.AddDbContext<ibContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
生成DbContext
:
Scaffold-DbContext "Connection String"
Microsoft.EntityFrameworkCore.SqlServer -Verbose -o {output folder} -t {table to update} -force
最佳答案
尝试以下操作:
- 确保通过 SQL Server 配置管理器启用 TCP/IP 协议(protocol)。另外,请确保未配置自定义端口,for detailed info
- 从远程主机(您尝试连接 SQL Server 的位置)的命令提示符处执行
telnet HC-SERVER-04 1433
如果第 2 步失败:在 SQL Server 的防火墙中使用端口号 1433
和 1434
创建规则以接受传入连接,然后尝试再次telnet,如果telnet工作,应用程序应该能够连接
- 如果进入防火墙后不起作用:重新启动
SQL Browser
服务 SQL Browser
服务不成功,请按如下方式更改连接字符串:
Server=HC-SERVER-04,1433;Database=IBCore_Lange;User Id=sa;password=XXX
关于c# - .NET Core 无法连接到远程 SQL Server 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57509997/