我在计算机上创建了一个 SQL Server 数据库,我使用 SQL Server Management Studio 来管理该数据库。
然后我添加了一个登录名,并为该登录名选择了 SQL Server 身份验证。我可以通过 SSMS 使用此登录名和密码连接到数据库,但无法在 ASP.NET 中执行此操作。
我使用这样的连接字符串:
Server=serverName;Database=databaseName;User Id=userName;Password=password;
我确定代码中一切正常,问题一定出在错误的连接字符串或错误的数据库配置中。
有人有什么想法吗?我从连接属性中获取 SSMS 的连接字符串数据。我从同一台计算机连接。
这是应该连接到数据库的代码:
public class DatabaseService
{
private readonly string _connectionString = ...;
public IEnumerable<Country> GetCountries()
{
using var connection = new SqlConnection(_connectionString);
connection.Open();
using var cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT ID, CountryName FROM Countries";
var dr = cmd.ExecuteReader();
var countries = new List<Country>();
while (dr.Read())
{
var country = new Country()
{
Id = Convert.ToInt32(dr["ID"]),
Name = dr["CountryName"].ToString()
};
countries.Add(country);
}
connection.Close();
return countries;
}
}
[Route("api/countries")]
[ApiController]
public class CountriesController : ControllerBase
{
private DatabaseService _dbService;
public CountriesController()
{
_dbService = new DatabaseService();
}
[HttpGet]
public IActionResult GetCountry()
{
IEnumerable<Country> countries = _dbService.GetCountries();
return Ok(countries);
}
}
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Internal connection fatal error.
数据库启用了 SQL Server 和 Windows 身份验证模式
解决方案:
<InvariantGlobalization>true</InvariantGlobalization> => <InvariantGlobalization>false</InvariantGlobalization>
我只是在使用 Microsoft.Data.SqlClient 而不是 System.Data.SqlClient 之后才看到这一点,因为它以可读的方式显示错误消息。