c# - .NET Core 无法连接到远程 SQL Server 数据库

标签 c# sql-server .net-core

我有一个 .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

最佳答案

尝试以下操作:

  1. 确保通过 SQL Server 配置管理器启用 TCP/IP 协议(protocol)。另外,请确保未配置自定义端口,for detailed info
  2. 从远程主机(您尝试连接 SQL Server 的位置)的命令提示符处执行 telnet HC-SERVER-04 1433

如果第 2 步失败:在 SQL Server 的防火墙中使用端口号 14331434 创建规则以接受传入连接,然后尝试再次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/

    相关文章:

    c# - 其中 T : class to VB

    c# - AutoMapper:映射记录类型问题

    c# - 什么会导致 EntityCommandDefinition.ExecuteStoreCommands 中的 EntityCommandExecutionException?

    java - 在 Spring Data JPA 中保留两个不同模式之间具有父子关系的表

    Docker - 如何连接到 SSL 上的 host.docker.internal?

    c# - 如何在 net.core 3.1 上使用 DI 正确配置身份核心?

    asp.net-core - 如何在 .NET Core 2.0 中获取登录用户的用户 ID?

    c# - 如何在 CosmosSDK v3+ 的 FeedResponse 中提供模拟值?

    c# - 在内容页 ASP.NET 中使用时,Javascript 不返回正确的值

    sql - 计算 T-SQL 表中成对出现的次数