在服务.NET Core中获取appsettings.json值

时间:2018-06-22 11:01:50

标签: c# .net asp.net-core .net-core appsettings

我有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类之外访问这些值?

2 个答案:

答案 0 :(得分:2)

您应该在ConfigureServices中注册配置:

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

答案 1 :(得分:1)

您可以查看我的code here了解详情。基本上我想阅读电子邮件设置,我的电子邮件设置的结构看起来像这样

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

然后,我需要定义一个这样的类来保存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; }
    } 

最后,我将其插入服务类或您想要的任何内容

private readonly IOptions<EmailSettings> _emailSetting;

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

然后致电

var something = _emailSetting.Value.SenderName

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

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

**请注意,此示例可帮助您在服务类(例如类库)中读取appSetting,或者我们可以从主mvc应用程序外部访问appsetting数据。