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:
- Configuration in ASP.NET Core – Configuration in ASP.NET Core | Microsoft Learn
- Options pattern in ASP.NET Core – Options pattern in ASP.NET Core | Microsoft Learn
- Configure an App Service app – Configure apps – Azure App Service | Microsoft Learn
- What is Azure App Configuration? – What is Azure App Configuration? | Microsoft Learn
- Environment variables and app settings in Azure App Service – Environment variables and app settings reference – Azure App Service | Microsoft Learn
Learn more about Audio Notes here.
Leave a Reply