api - 如何从 JSON 字符串配置自定义对象?
问题描述
我想使用包含我的 smtp 设置配置 JSON 的系统环境变量在启动时配置我的自定义 SmtpSettings 对象。
这是我从secrets
/检索配置的实际工作代码appsettings.json
:
//Configure email service for DI
services.Configure<SmtpSettings>(Configuration.GetSection("SmtpSettings"));
services.AddSingleton<IMailService, MailService>();
我想获得这样的东西:
services.Configure<SmtpSettings>(Environment.GetEnvironmentVariable("SMTP_SETTINGS") ?? Configuration.GetSection("SmtpSettings"));
如果可用,我需要使用系统环境变量,否则使用secrets
/中包含的标准配置appsettings.json
。
如何获得所需的实现?
解决方案
我想你可以在
var envVar = Environment.GetEnvironmentVariable("SMTP_SETTINGS");
if (string.IsNullOrEmpty(envVar))
{
services.Configure<SMTP_SETTINGS>(Configuration.GetSection("SMTP_SETTINGS"));
}
else
{
services.Configure<SMTP_SETTINGS>(options =>
{
var smtpSettings = JsonConvert.DeserializeObject<SMTP_SETTINGS>(envVar);
options.Host = smtpSettings.Host;
options.Port = smtpSettings.Port;
});
}
如果您将环境变量作为以下内容传递
"SMTP_SETTINGS":"{"端口": 567, "主机": "smtp.com"}"
推荐阅读
- android-studio - 如何将语音识别与 Porcupine 一起使用
- java - 如何在java中将转换为字节数组的文本文件内容写入另一个文件
- cypress - 赛普拉斯:网站的一部分是 http 其他是 https 我可以绕过不同的来源吗?
- python - 如何在 python 中使用@attribue 和清理数据集?
- sql - SQL 计算 - 我想将本月的开始数量设为上个月的结束数量
- python - 如何按第一个字母然后第二个字母等对数组中的元素进行排序?
- c++ - 在cpp中计算时间
- javascript - 使用 GET 接收 base64 而不下载文件
- html - 使用许多标签Bootstrap4在col内水平对齐
- java - TimeLINE javaFX 线程