在服务 .net 核心中获取 appsettings.json 个值

Get appsettings.json values in service .net core

我有 appsettings.json 个文件,我想在其中声明文件路径。

"Paths": { "file": "C:/file.pdf" }

我想在我的服务中访问这个值,我尝试这样做:

public class ValueService: IValueService
{
    IConfiguration Configuration { get; set; }

    public MapsService(IConfiguration configuration)
    {
        this.Configuration = configuration;
    }


    public string generateFile()
    {

           var path = Configuration["Paths:file"] ;
    }

}

但是我得到 var path

的空值

Startup.cs 文件声明了 appsettings.json,因为它从那里获取连接字符串。是否可以在 startup.cs class 之外访问这些值?

您应该在 ConfigureServices 中注册配置:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSingleton<IConfiguration>(Configuration);
}

详情可以看我的code here。基本上我想阅读电子邮件设置,我的电子邮件设置结构如下所示

"EmailSettings": {
    "MailServer": "",
    "MailPort": "",
    "Email": "",
    "Password": "",
    "SenderName": "",
    "Sender": "",
    "SysAdminEmail": ""
  }

然后我需要像这样定义一个 class 来保存 appSetting

中的所有信息
 public class EmailSettings
    {
        public string MailServer { get; set; }
        public int MailPort { get; set; }
        public string SenderName { get; set; }
        public string Sender { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string SysAdminEmail { get; set; }
    } 

最后我注入我的服务class或者你想要的任何东西

private readonly IOptions<EmailSettings> _emailSetting;

public EmailSender(IOptions<EmailSettings> emailSetting)
{
    _emailSetting = emailSetting;
}

然后打电话给

var something = _emailSetting.Value.SenderName

可以找到电子邮件发件人文件here

如果您有任何问题,请告诉我。

** 注意这个例子可以帮助你阅读 appSetting inside service class like class library 或者我们可以从外部主 mvc app 访问 appsetting 数据。