How to update values into appsetting.json?

前端 未结 4 2122
半阙折子戏
半阙折子戏 2020-11-27 12:39

I am using the IOptions pattern as described in the official documentation.

This works fine when I am reading values from appsetting.json,

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 13:29

    I hope that my scenario covers your intent, I wanted to override the appsettings.json values if there are environment variables passed to the app at startup.

    I made use of the ConfigureOptions method that is available in dotnet core 2.1.

    Here is the Model that is used for the JSON from appsettings.json

    public class Integration
    {
     public string FOO_API {get;set;}
    }
    

    For the services in the statup.cs:

    var section = Configuration.GetSection ("integration");
                services.Configure (section);
                services.ConfigureOptions();
    

    Here is the implemenation:

    public class ConfigureIntegrationSettings : IConfigureOptions
        {
            public void Configure(Integration options)
            {
                if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("FOO")))
                    options.FOO_API = Environment.GetEnvironmentVariable("FOO_API");
    
            }
        }
    

    so if there is no value set it falls back to the appsettings.json

提交回复
热议问题