Get appsettings.json values in service .net core

2019-05-15 23:53发布

问题:

I have appsettings.json file where I want to declare paths to files.

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

I want to access this value in my service, I try it to do like this:

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

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


    public string generateFile()
    {

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

}

however I get null values for var path

Startup.cs file has appsettings.json declared as it takes connection string from there. Is it possible to access these values outside startup.cs class?

回答1:

You should register Configuration in ConfigureServices:

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


回答2:

You can see my code here for detail. Basically I want to read email setting and the structure of my email setting look like this

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

Then I will need to define a class like this to hold all of information in 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; }
    } 

Finally I inject into my service class or whatever you want

private readonly IOptions<EmailSettings> _emailSetting;

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

then call

var something = _emailSetting.Value.SenderName

Email sender file can be found here

If you have any question just let me know.

** Note this example help you read appSetting inside service class like class library or we can access appsetting data from outside main mvc app.