System.InvalidOperationException:连接字符串 'DefaultConnection' 格式无效。预期格式:'Server=tcp:...;Database=...;User ID=...;Password=...;'
System.InvalidOperationException: The ConnectionString 'DefaultConnection' has an invalid format. Expected format: 'Server=tcp:...;Database=...;User ID=...;Password=...;'
ID: cloud/azure-app-service-connection-string-format
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Azure App Service Windows | active | — | — | — |
| Azure App Service Linux | active | — | — | — |
| .NET 8 | active | — | — | — |
根因分析
Azure App Service 应用设置中存储的连接字符串通常语法错误(例如缺少分号、键名错误或对 SQL 数据库使用了非 SQL Server 格式)。
English
Azure App Service connection strings stored in app settings often have incorrect syntax (e.g., missing semicolons, wrong key names, or using non-SQL Server format for SQL Database).
官方文档
https://learn.microsoft.com/en-us/azure/app-service/app-service-key-vault-references解决方案
-
在应用设置中使用适用于 Azure SQL 数据库的正确格式:Server=tcp:<server>.database.windows.net,1433;Database=<db>;User ID=<user>@<server>;Password=<password>;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
-
从 Azure 门户获取连接字符串:转到 SQL 数据库 -> 连接字符串 -> ADO.NET,复制确切字符串并粘贴到应用服务的 '连接字符串' 部分,类型选择 'SQLAzure'。
-
使用正确的语法引用 Key Vault:@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/myconnectionstring/)。确保应用服务在保管库上具有 'Key Vault Secrets User' 角色。
无效尝试
常见但无效的做法:
-
95% 失败
Adding extra quotes around the connection string in app settings causes parsing errors.
-
80% 失败
Using Key Vault references without proper syntax like @Microsoft.KeyVault(SecretUri=...) results in the raw reference string being used as the connection string.
-
85% 失败
Copying a connection string from SQL Server Management Studio that includes 'Trusted_Connection=True' fails because Azure SQL requires SQL authentication.