c# - 在 .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是跨平台的,因此无法访问键。(是的?)
如果此平台不支持连接字符串的解密,是否有一些首选的替代方法来加密/解密连接字符串?
我从高处和低处看了看,但似乎找不到任何东西。
注意:解密加密连接字符串的能力是必不可少的!
解决方案
该类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;"
},
}
推荐阅读
- java - Spring Security - 编码密码看起来不像 BCrypt
- java - 在不同的事件循环上提供不同的 webflux 端点
- android - 为什么 Android 会阻止我的 OkHttp 请求
- meraki-api - Meraki REST API - 缺少端点?
- c# - 将图像添加到窗口标题栏
- sql - 使用PostgreSQL根据特定列在数组中查找重复值
- ionic-framework - 如何混淆cordova插件java代码
- angular - Angular 8 - HttpInterceptor - 读取响应标头
- svn - 如何将 jnilibs 提交到 svn
- directus - Directus 自定义端点权限