[英]How to get connection string in run-time with password in ASP.NET Core
Here i am using appsettings.json file for connection string. 在这里,我使用appsettings.json文件作为连接字符串。 I got connection string in runtime without password.
我在运行时没有密码就得到了连接字符串。
Example: 例:
((MySql.Data.MySqlClient.MySqlConnection)DataContext.Database.GetDbConnection()).ConnectionString
Please help to get password in runtime. 请帮助在运行时获取密码。
Thank in advance. 预先感谢。
You should try to get the connection string from Configuration, not from a DbConnection
. 您应该尝试从Configuration而不是
DbConnection
获取连接字符串。 For example, if appsettings.json
contains the following, you can get the connection string via Configuration.GetConnectionString("mydb")
. 例如,如果
appsettings.json
包含以下内容,则可以通过Configuration.GetConnectionString("mydb")
获得连接字符串。
{
"ConnectionStrings": {
"mydb": "server=DBSERVER;user=myuser;password=pwd;database=DB"
}
}
That said, if you do have a DbConnection
(or MySqlConnection
) object, you can get the password from the MySqlConnection.ConnectionString
property if one or both of the following are true: 就是说,如果您确实具有
DbConnection
(或MySqlConnection
)对象,则如果以下一项或两项为真,则可以从MySqlConnection.ConnectionString
属性获取密码:
PersistSecurityInfo=true;
PersistSecurityInfo=true;
. If you're able to modify the original connection string your application is using, you can add the PersistSecurityInfo=true
flag. 如果您能够修改应用程序使用的原始连接字符串,则可以添加
PersistSecurityInfo=true
标志。 Otherwise, you will need to get an unopened database connection in order to retrieve the full connection string, including the password. 否则,您将需要获得未打开的数据库连接才能检索完整的连接字符串,包括密码。
This is by design, for security reasons. 出于安全原因,这是设计使然。 From MSDN :
从MSDN :
The ConnectionString is similar to an OLE DB connection string, but is not identical.
ConnectionString与OLE DB连接字符串相似,但不相同。 Unlike OLE DB or ADO, the connection string that is returned is the same as the user-set ConnectionString, minus security information if the Persist Security Info value is set to false (default).
与OLE DB或ADO不同,返回的连接字符串与用户设置的ConnectionString相同,如果Persist Security Info值设置为false(默认值),则减去安全信息。 The .NET Framework Data Provider for SQL Server does not persist or return the password in a connection string unless you set Persist Security Info to true.
除非将Persist Security Info设置为true,否则SQL Server的.NET Framework数据提供程序不会持续存在或在连接字符串中返回密码。
So, try to add Persist Security Info=true;
因此,尝试添加
Persist Security Info=true;
in your connection string. 在您的连接字符串中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.