简体   繁体   English

在服务 .net core 中获取 appsettings.json 值

[英]Get appsettings.json values in service .net core

I have appsettings.json file where I want to declare paths to files.我有appsettings.json文件,我想在其中声明文件的路径。

"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但是我得到了var path空值

Startup.cs file has appsettings.json declared as it takes connection string from there. Startup.cs文件声明了appsettings.json因为它从那里获取连接字符串。 Is it possible to access these values outside startup.cs class?是否可以在startup.cs类之外访问这些值?

You should register Configuration in ConfigureServices:您应该在 ConfigureServices 中注册配置:

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

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然后我需要定义一个这样的类来保存 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. ** 请注意,此示例可帮助您在类库等服务类中读取 appSetting,或者我们可以从主 mvc 应用程序外部访问 appsetting 数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM