简体   繁体   English

更改ASP.NET Core中的配置文件

[英]Change configuration file in ASP.NET Core

I am trying to create a self-contained .NET Core Console Application. 我正在尝试创建一个独立的.NET Core控制台应用程序。 In my application, I have added a configuration file appsettings.json . 在我的应用程序中,我添加了一个配置文件appsettings.json。 The goal is now that I need to have the possibility to modify the configuration file while the application is running (and published) 现在的目标是,我需要有可能在应用程序运行(和发布)时修改配置文件

I have found several guides but they all point to the direction where I need to include the following function: 我找到了一些指南,但是它们都指向我需要包括以下功能的方向:

        public void ConfigureServices(IServiceCollection services)
    {
        // Adds services required for using options.
        services.AddOptions();

        // Register the IConfiguration instance which MyOptions binds against.
        services.Configure<DBSetting>(Configuration);

        // Add framework services.
        services.AddMvc();
    }

But when I do this all the methodes of services are red. 但是当我这样做时,所有的服务方法都是红色的。 If I look u IserviceCollection the doc says that it has become obsolete. 如果我查看IserviceCollection,则文档说它已经过时了。 I did add 我确实添加了

            var builder = new ConfigurationBuilder()
            .AddJsonFile(@"C:\Users\Maarten\Documents\Visual Studio 2015\Projects\CorporationBot\CorporationBotCore\appsettings.json", optional: true, reloadOnChange:true);                
        Configuration = builder.Build();

in my Program.cs which lets me fetch the data in my config file. 在我的Program.cs中,这使我可以获取配置文件中的数据。 Now I need a way to change my config while the application is running. 现在,我需要一种在应用程序运行时更改配置的方法。 Any up to date ways to do it? 有什么最新的方法吗?

According to Microsft configurations that are written into built-in providers are not persisted. 根据Microsft的配置,不会保留写入内置提供程序中的配置。 So you may need to write a custom provider and implement save there. 因此,您可能需要编写一个自定义提供程序并在其中实现保存。 Following link provides more info about asp.net configuration and a sample custom EF provider. 以下链接提供有关asp.net配置和示例自定义EF提供程序的更多信息。

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration?tabs=basicconfiguration https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration?tabs=basicconfiguration

As a side note, if the value tends to change at runtime.Database or some other place also can be a possible alternative. 附带说明一下,如果该值倾向于在运行时更改,则数据库或其他位置也可以作为替代方法。

Looks like you forgot to add or restore nuget packages related to configuration feature . 好像您忘记添加或还原与配置功能相关的nuget软件包。

And don't forget to add namespace: using Microsoft.Extensions.Configuration; 并且不要忘记添加名称空间: using Microsoft.Extensions.Configuration;

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

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