Get appsettings.json values in service .net core

泄露秘密 提交于 2019-12-22 10:43:30

问题


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.



来源:https://stackoverflow.com/questions/50986497/get-appsettings-json-values-in-service-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!