首页 > 解决方案 > 在 .NET Core 中,如何从 appsetting.json 读取并在 setter 方法中为对象赋值

问题描述

我在 appsettings.json 中有 SendGrid 电子邮件配置,我需要在 startup.cs 中进行初始化,我已经定义了类 EmailConfig,我想在其中分配来自 appsettings.json 的值,以便我可以在其他地方使用。

appsetting.json

"SendGridEmailSettings": {
    "SendGrid_API_Key": "MY-Key-XYZ",
    "From": "info@organisation.ltd"

}

EmailConfig 类

  public class EmailConfig : IEmailConfig
{
    public string API_Key { get; set; }
    public string From { get; set; }
}

在我的核心课程中,我需要将此值读取为

public mailConfig emailConfig { get; set; } 

标签: .net-core

解决方案


我将首先重命名 EmailConfig 字段以匹配设置:

public class EmailConfig
{
    public string SendGrid_API_Key { get; set; }
    public string From { get; set; }
}

在您的 startup.cs 的 ConfigureServices 方法中,添加:

var emailConfig = new EmailConfig();
Configuration.GetSection("SendGridEmailSettings").Bind(emailConfig);

此时,emailConfig 对象具有 appsetting.json 值。

如果我可以建议的话,我会创建一个专门用于发送电子邮件的服务,并将 EmailConfig 对象传递给该服务一次:

public class EmailService : IEmailService
{
    private readonly EmailConfig _emailConfig;

    public EmailService(EmailConfig emailConfig)
    {
        _emailConfig = emailConfig
    }
}

您现在可以通过在您的 startup.cs 的 ConfigureServices 方法中添加以下内容来将 emailConfig 对象发送到服务:

services.AddTransient<IEmailService, EmailService>(_ =>
    new EmailService(emailConfig));

推荐阅读