【问题标题】:Decrypting app.config connection strings in .Net Core 3.1在 .Net Core 3.1 中解密 app.config 连接字符串
【发布时间】:2022-02-19 09:38:12
【问题描述】:

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

// 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-core connection-string app-config .net-framework-4.8


【解决方案1】:

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 类的实例,该类已记录在 here 中,但与 ConfigurationManager 非常相似

config.json 的示例:

{
  "ConnectionStrings": {
    "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
  },
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 2016-02-10
  • 2012-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多