默认情况下,Microsoft 的 SqlConnection 会在.ConnectionString
您连接后为您删除密码:
connection.ConnectionString = "Data Source=screwdriver;User ID=MrSnrub;Password=smithers;";
connection.Open();
>connection.ConnectionString
"Data Source=screwdriver;User ID=MrSnrub;Password=smithers;"
您可以通过指定Persist Security Info=true来覆盖此行为;:
String cs = "Data Source=screwdriver;User ID=MrSnrub;Password=smithers;Persist Security Info=true";
conn.ConnectionString = cs;
conn.Open();
>conn.ConnectionString
"Data Source=screwdriver;User ID=MrSnrub;Password=smithers;Persist Security Info=true"
使用安全字符串
另一种方法是使用 .NET 4.5 的方法通过SqlCredential对象将密码作为SecureString传递给SqlConnection :
SecureString pwd = AzureKeyVault.GetSettingSecure("DbPassword");
SqlCredential cred = new SqlCredential("MrSnrub", pwd);
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=screwdriver;";
conn.Credential = cred;