问题描述
我为控制台应用程序提供以下代码:
// 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是“兼容的”,以便访问配置文件,但解密不是因为解密的密钥存储在Framework中,而是因为Core是跨平台的,因此没有访问密钥。 (是吗?)
如果此平台不支持连接字符串的解密,那么除了加密/解密连接字符串之外,还有其他更好的选择吗?
我看上去高低不一,但似乎什么也找不到。
注意:解密加密的连接字符串的能力至关重要!
谢谢。
解决方法
DotNetCore中已弃用ConfigurationManager
类,已将其替换为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
类的实例,该实例记录在here中,但与ConfigurationManager
十分相似
config.json
的示例:
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
},}