[英]Decrypting app.config connection strings in .Net Core 3.1
我有以下控制台應用程序代碼:
// Get the app config file.
var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Get the sections to unprotect.
ConfigurationSection connStrings = configuration.ConnectionStrings;
string connection = null;
if (connStrings != null)
{
// UNPROTECT
connStrings.SectionInformation.UnprotectSection();
connection = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
}
這段代碼在 Framework 4.8 上工作得很好,但是當我在 Core 3.1 上嘗試時,它在“UNPROTECT”代碼處拋出“PlatformNotSupportedException”。
這是在同一個工作站和一切。
ConfigurationManager 和 SectionInformation 的官方文檔都顯示了與 Core 3.0 和 3.1 的兼容性。
我猜為了方便訪問配置文件,這些類與 Core“兼容”,但解密不是因為解密的密鑰存儲在框架中,而是 Core 是跨平台的,因此無法訪問鍵。 (是的?)
如果此平台不支持解密連接字符串,是否有一些首選的替代加密/解密連接字符串的方法?
我看了高低,但似乎無法找到任何東西。
注意:解密加密連接字符串的能力是必不可少的!
謝謝。
ConfigurationManager
類在 DotNetCore 中已被棄用,它已被替換為IConfiguration
類,您可以使用ConfigurationBuilder
類構造它,這是加載 json 文件的示例(請注意,您需要兩個 nuget 依賴項,它們是Microsoft.Extensions.Configuration
和Microsoft.Extensions.Configuration.Json
):
var config = new ConfigurationBuilder()
.AddJsonFile("Config.json", true) // bool to say whether it is optional
.Build()
如前所述,這將為您提供IConfiguration
類的一個實例,該實例記錄在此處,但與ConfigurationManager
非常相似
config.json
示例:
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
},
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.