首页 > 解决方案 > 在 .Net Core 3.1 中解密 app.config 连接字符串

问题描述

我有以下控制台应用程序代码:

// 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 上尝试时,它会抛出

PlatformNotSupportedException

在“UNPROTECT”代码处。

这是在同一个工作站和一切。

ConfigurationManager 和 SectionInformation 的官方文档显示了与 Core 3.0 和 3.1 的兼容性。

我猜这些类与Core“兼容”是为了方便访问配置文件,但解密不是因为解密的密钥存储在Framework中,而是Core是跨平台的,因此无法访问键。(是的?)

如果此平台不支持连接字符串的解密,是否有一些首选的替代方法来加密/解密连接字符串?

我从高处和低处看了看,但似乎找不到任何东西。

注意:解密加密连接字符串的能力是必不可少的!

标签: c#.net-coreconnection-stringapp-config.net-framework-4.8

解决方案


该类ConfigurationManager在 DotNetCore 中已被弃用,它已被替换为IConfiguration您可以使用该类构建的ConfigurationBuilder类,这是加载 json 文件的示例(请注意,您需要两个 nuget 依赖项,即Microsoft.Extensions.ConfigurationMicrosoft.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;"
  },
}

推荐阅读