首页 > 解决方案 > 如何从 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

如何获得所需的实现?

标签: apiasp.net-core-3.1asp.net-core-configuration

解决方案


我想你可以在

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"}"


推荐阅读