kosnkov
kosnkov

Reputation: 5941

Read values from appsettings.json before configuration.build

Is that possible to read values from appsettings.json before configuration.build ?

i need to get endpoint, clientId, secret and tenant to bind configuration with azure app configuration

Configuration = builder.AddAzureAppConfiguration(options =>
           {
              //here i need to get some values from appsettings.json

           }).Build()

Upvotes: 3

Views: 1729

Answers (3)

Vinicius Bassi
Vinicius Bassi

Reputation: 504

You can use a ConfigurationBuilder as such:

var builder = new ConfigurationBuilder()
                    .SetBasePath("yourJsonPath")
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
var config = builder.Build();

then you can retrieve the value you need:

config.GetSection("AppConfig:Endpoint").Value

or just

 config.GetSection("ClientId").Value

Depending on how your JSON is built.

Upvotes: 2

J. Campbell
J. Campbell

Reputation: 730

It's not possible.

Here are two examples of a scenario similar to yours in the Azure App Configuration GitHub examples:

Console Application

https://github.com/Azure/AppConfiguration-DotnetProvider/blob/e227b0b454370751c2ddbebb143fd6e02a07c47b/examples/ConsoleApplication/Program.cs#L36

The example shows that the ConfigurationBuilder is built to obtain an intermediate IConfiguration that is then used to provide a connection string for adding Azure App Configuration to the builder.

ASP.NET Core Web Application

https://github.com/Azure/AppConfiguration-DotnetProvider/blob/e227b0b454370751c2ddbebb143fd6e02a07c47b/examples/ConfigStoreDemo/Program.cs#L26

In the ASP.NET Core web application example the same pattern is used with the framework provided IConfigurationBuilder

Upvotes: 2

JHBonarius
JHBonarius

Reputation: 11271

I'm not sure about this, as I usually use the WebHostBuilder, but I think it should be something like:

var settings = builder.Build();
Configuration = builder.AddAzureAppConfiguration(options =>
{
    options.Connect(settings["ConnectionStrings:AppConfig"])
}).Build();

edit: note I assumed you already added appsettings.json to the builder. If not, you need to add

var env = [something like]hostingContext.HostingEnvironment;

config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

Upvotes: 1

Related Questions