You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置连接字符串使C#应用通过SQL Server认证连接Docker容器SQL Server

问题描述

原本运行在域环境中的C#应用与SQL Server数据库,现已将数据库恢复至无域支持环境(SQL Server运行于Docker容器内)。通过ODBC使用SQL Server认证可成功连接,ODBC配置信息如下:

Server         10.0.0.1
LoginID        <username of dbOwner>
Password       <password>
Default db     ThisProject

但C#应用使用各类常规连接字符串变体时,始终返回错误 “Login failed: The login is from an untrusted domain”,所用连接字符串示例:

data source=10.0.0.1;
initial catalog=ThisProject;
integrated security=False; 
User Id=<dbOwner>;
Password=<password>;
Trusted_Connection=False;

已尝试调整以下参数的不同取值:

integrated security=False, True, SSPI, <missing>;
trusted_Connection=False, True;
解决方案

核心问题定位

错误提示明确说明:你的C#应用仍在尝试使用Windows身份验证(域/本地系统账号),而非指定的SQL Server账号。即便显式设置了禁用Windows认证的参数,也可能因参数冲突、拼写错误或隐性配置覆盖导致失效。

正确的连接字符串配置

使用最简且无歧义的SQL Server认证连接字符串,避免冗余参数引发的解析冲突:

"Server=10.0.0.1;Database=ThisProject;User Id=<dbOwner>;Password=<password>;"

关键注意事项

  • 无需同时设置integrated security和Trusted_Connection:这两个参数功能完全等效,同时设置可能导致解析逻辑混乱。当你明确指定User Id和Password时,SQL Client会自动切换到SQL Server认证模式,可完全省略这两个参数。
  • 检查账号拼写:确保User Id对应的账号名与ODBC配置中的<username of dbOwner>完全一致(SQL Server默认不区分大小写,但部分场景可能受实例配置影响)。
  • 验证Docker容器的SQL Server认证模式:Docker部署的SQL Server默认可能仅启用Windows认证,需切换为混合认证模式(Windows+SQL Server认证)。可执行以下SQL语句检查并修改:
    -- 查看当前认证模式
    SELECT name, value_in_use FROM sys.configurations WHERE name = 'server authentication';
    -- 若value_in_use为1(仅Windows认证),执行以下修改(需重启SQL Server容器)
    EXEC sp_configure 'show advanced options', 1;
    RECONFIGURE;
    EXEC sp_configure 'server authentication', 2; -- 2代表混合认证模式
    RECONFIGURE;
    
  • 排查应用配置优先级:如果应用使用appsettings.json、web.config或环境变量存储连接字符串,需确保没有其他配置项覆盖当前设置,或存在继承的Windows认证配置。

额外排查步骤

  • 使用SqlConnectionStringBuilder生成连接字符串,避免手动拼写错误:
    var builder = new SqlConnectionStringBuilder();
    builder.DataSource = "10.0.0.1";
    builder.InitialCatalog = "ThisProject";
    builder.UserID = "<dbOwner>";
    builder.Password = "<password>";
    builder.IntegratedSecurity = false;
    string connectionString = builder.ToString();
    
  • 验证网络连通性:确保Docker容器的SQL Server默认端口(1433)已对外开放,且C#应用所在机器能正常访问该端口。

内容的提问来源于stack exchange,提问作者Omnitec

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:50:44