System.InvalidOperationException:连接字符串 'DefaultConnection' 的格式无效。预期格式:'Server=tcp:myserver.database.windows.net,1433;Database=mydb;User ID=myuser;Password=mypassword;Encrypt=True;TrustServerCertificate=False;'
System.InvalidOperationException: The ConnectionString 'DefaultConnection' has an invalid format. Expected format: 'Server=tcp:myserver.database.windows.net,1433;Database=mydb;User ID=myuser;Password=mypassword;Encrypt=True;TrustServerCertificate=False;'
ID: cloud/azure-sql-connection-string-format-invalid
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Microsoft.Data.SqlClient 5.1.0 | active | — | — | — |
| System.Data.SqlClient 4.8.5 | active | — | — | — |
| .NET 8 | active | — | — | — |
| .NET Framework 4.8 | active | — | — | — |
根因分析
为 Azure SQL 数据库提供的连接字符串未遵循所需的格式,通常是由于缺少 'Server'、'Database' 或 'User ID' 等关键字,或使用了错误的分隔符。
English
The connection string provided for Azure SQL Database does not follow the required format, often due to missing keywords like 'Server', 'Database', or 'User ID', or using incorrect separators.
官方文档
https://learn.microsoft.com/en-us/azure/azure-sql/database/connect-query-dotnet-core?view=azuresql解决方案
-
Construct the connection string exactly as: Server=tcp:yourserver.database.windows.net,1433;Database=yourdb;User ID=youruser;Password=yourpassword;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;. Example in appsettings.json: "DefaultConnection": "Server=tcp:myserver.database.windows.net,1433;Database=mydb;User ID=myuser;Password=mypassword;Encrypt=True;TrustServerCertificate=False;"
-
Use Azure SQL connection string builder in code. Example in C#: var builder = new SqlConnectionStringBuilder { DataSource = "tcp:myserver.database.windows.net,1433", InitialCatalog = "mydb", UserID = "myuser", Password = "mypassword", Encrypt = true, TrustServerCertificate = false }; var connectionString = builder.ConnectionString;
无效尝试
常见但无效的做法:
-
80% 失败
JSON requires proper string escaping; trailing semicolons or line breaks break parsing. The runtime expects a single line string.
-
70% 失败
Azure SQL requires the 'tcp:' prefix for the server name to enforce TCP/IP connection; omitting it causes format rejection.