Software Architect / Microsoft MVP (AI) and Technical Author

ASP.NET Core, C#, General Development

Using Configuration Builder to Read Application Settings Stored in appsettings.json with Visual Studio 2022 and .NET 7.0

Sometimes you want to quickly read settings without any of the regular dependency injection or typical ceremony such as creating a strong typed object to store values.

For example, when creating the Audio Notes MVP, I wanted a quick way to read the Azure AI Language API endpoint and API key.

Example JSON File

You can see the appsettings.json file with these values here:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AppSettings": {
    "TextAnalyticsEndpoint": "https://{endpoint}.azure.com/",
    "TextAnalyticsAPIKey": "{api-key}"
  },
  "AllowedHosts": "*"
}

Reading App Setting Properties

Here is the C# that’s needed to read these settings:

public async Task<JsonResult> SummarizeTextAsync(string document)
        {
            try
            {
                var MyConfig = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
                var TextAnalyticsEndpoint = MyConfig.GetValue<string>("AppSettings:TextAnalyticsEndpoint");
                var TextAnalyticsAPIKey = MyConfig.GetValue<string>("AppSettings:TextAnalyticsAPIKey");

                TextAnalyticsService ta = new TextAnalyticsService(TextAnalyticsEndpoint, TextAnalyticsAPIKey);

                var reply = await ta.SummarizeSpeechTranscript(document);
                
                return Json(reply);
            }
            catch(Exception ex)
            {
                return new JsonResult("Error:" + ex.Message);
            }
        }

 

The configuration builder loads the settings in appsettings.json file.  Settings are read in lines 13-14.

That’s it.

Summary

Naturally, you don’t want to have this in every controller or class and would probably create a strongly typed settings class to store important settings or read these from Azure Key Vault.

For rapid development of the Audio Notes MVP however, I just wanted a quick solution, and this makes that possible.

Further Resources and Reading

The following links and resources will help you learn more about app settings, best practice, and other approaches to implementing:

 

Learn more about Audio Notes here.

JOIN MY EXCLUSIVE EMAIL LIST
Get the latest content and code from the blog posts!
I respect your privacy. No spam. Ever.

Leave a Reply