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

ASP.NET Core应用配置SQL Server账号认证仍用Windows登录报错求助

解决ASP.NET Core应用未使用配置的SQL账号连接数据库的问题

你的问题核心是配置了SQL Server身份验证的连接字符串,但应用实际仍使用Windows身份验证发起连接,导致登录失败。可以从以下几个方向排查解决:

1. 确认代码中正确读取了目标连接字符串

检查你的DbContext注册代码,确保确实读取了QuickKartDBConnectionString这个配置项,而非硬编码Windows身份验证的连接字符串或使用了其他配置名。

ASP.NET Core 6+(Program.cs)示例:

var builder = WebApplication.CreateBuilder(args);

// 注册DbContext时指定正确的连接字符串
builder.Services.AddDbContext<ProductDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("QuickKartDBConnectionString")));

旧版本Startup.cs示例:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ProductDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("QuickKartDBConnectionString")));
}

2. 验证连接字符串的参数正确性

你的连接字符串已设置Integrated security=False,需额外确认:

  • 参数拼写无误:Integrated Security(注意空格)或Trusted_Connection是等价的,若写成IntegratedSecurity(无空格)会被忽略,默认使用Windows身份验证。
  • User ID和Password参数名无拼写错误(避免写成UserId或Pwd,保持与配置一致更稳妥)。
  • 服务器名称MyServerName是SQL Server的正确实例名(例如默认实例需写成MyServerName\SQLEXPRESS,或直接使用IP地址)。

3. 检查是否有配置源覆盖了appsettings.json的内容

ASP.NET Core配置读取优先级为:命令行参数 > 环境变量 > appsettings.{Environment}.json > appsettings.json。以下情况会覆盖你在appsettings.json中的配置:

  • 系统环境变量中设置了同名的ConnectionStrings__QuickKartDBConnectionString(用双下划线分隔层级)。
  • launchSettings.json的environmentVariables节点中配置了该连接字符串。
  • 启动应用时通过命令行参数指定了连接字符串。

可临时添加日志输出确认实际读取的连接字符串内容:

var connString = builder.Configuration.GetConnectionString("QuickKartDBConnectionString");
Console.WriteLine($"当前使用的连接字符串:{connString}");

4. 确认SQL Server端的登录配置正确

即使连接字符串正确,也需确保SQL Server中:

  • 已创建User1这个SQL登录名,且登录状态为启用。
  • User1已映射到ProductDB数据库的用户,并拥有该数据库的访问权限(如db_datareader、db_datawriter角色)。

可在SQL Server Management Studio中执行以下语句验证:

-- 检查登录名是否存在
SELECT name FROM sys.server_principals WHERE name = 'User1';

-- 检查数据库用户是否存在并映射
SELECT dp.name FROM sys.database_principals dp
JOIN sys.server_principals sp ON dp.sid = sp.sid
WHERE dp.name = 'User1' AND dp.type_desc = 'SQL_USER';

报错信息:
Cannot open database "ProductDB" requested by the login. The login failed.
Login failed for user 'mydomain\kcs.sahoo'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 10:33:37