How to Read App Settings in C#

This post was virtually recently updated on February 25th, 2022.

6 min read.

This article explains how you can access an Azure Function's Application/Environment settings/variables from your C# code. Different versions of Azure Functions have dissimilar ways to access the Azure Function settings, but this page should explicate the easiest way to become your application setting values for each Azure Functions version!

While this is something I need often, it has been another piffling thing, that I always forget – so meliorate document it somewhere.

How to go application settings in different runtime versions of Azure Functions?

This has changed betwixt dissimilar versions of Azure Functions runtime – so I'm describing what should work for v3 (the latest runtime version), v2, and v1.

Note, that a lot of the examples below are not entirely specific to Azure Functions – they bear witness how to admission app.config or local.settings.json values in C# regardless of the exact implementation, whether it's a webjob, ASP.NET application, .Net Console program, or something else. This post is written from Azure Functions' viewpoint, though.

Accessing the settings in Azure Functions Runtime Version 3

Okay, then if you'll take a wait at the style the Application Settings (or whatsoever you want to call them) are accessed for the v2 runtime of Azure Functions, you can see they made it extremely granular. It's very functional, merely it tin can be a scrap of a pain in the backside when just setting up ane function.

Now, in v3 they made it far more straightforward! The example below shouldn't crave any NuGet packages, and just works!

Crawly! Just update your using statements similar shown:

          // C# ConfigurationBuilder instance for Azure Functions v3 runtime using System; using System.IO;  ...  // y'all'll need this : using Microsoft.Extensions.Configuration;   namespace YourApp {   public static grade YourClass   { 	     [FunctionName("FunctionName")]     public static async Job<IActionResult> Run(       [HttpTrigger(AuthorizationLevel.Anonymous, "mail service", Route = cipher)] HttpRequest req,       // You'll demand this to add the        // local.settings.json file for local execution :       ExecutionContext context,        ILogger log)     { 	  var config = new ConfigurationBuilder() 	    .SetBasePath(context.FunctionAppDirectory)             // This gives you access to your application settings              // in your local development environment 	    .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)              // This is what really gets you lot the              // awarding settings in Azure 	    .AddEnvironmentVariables()  	    .Build(); 				 	    string appsettingvalue = config["appsettingkey"];     }   } }        

Remember to add the ExecutionContext equally an injection to your Azure Role.

This piece of code fetches the configuration keys and values from Surroundings Variables, and a local file called "local.settings.json". This file is typically added to your Visual Studio Azure Functions projection when information technology was first created. However, if you're jumping on a projection that was created past someone else, they might accept .gitignore'd the configuration file (as they probably should), and so you lot didn't get the file.

And what should your local.settings.json file look like? Something like beneath:

          {   "IsEncrypted": imitation,   "ConnectionStrings": {     "DefaultConnection": "Server=(localdb)\\mssqllocaldb;..."   },   "Values": {     "appsettingkey":  "value"    } }        

And with that, you should be expert in Azure Functions v3.

Accessing the settings in Azure Functions Runtime Version 2

For the second generation of Azure Functions, the code to access the Application Settings is the same, simply the configuration steps are a bit different. Not quite as straightforward as v1 (you lot'll see that further below) or superbly easy as v3 (above), but flexible for sure.

ConfigurationManager is not used similar in v1. Instead, you're supposed to use ConfigurationBuilder. Check out the lawmaking instance below!

          // C# ConfigurationBuilder example for Azure Functions v2 runtime  using Organization; using Organization.IO;  ...  using Microsoft.Extensions.Configuration; // <- you lot'll need this  namespace YourApp {   public static class YourClass   { 	     [FunctionName("FunctionName")]     public static async Task<IActionResult> Run(       [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = nil)] HttpRequest req,       // You'll need this to add the local.settings.json        // file for local execution:       ExecutionContext context,        ILogger log)     { 	  var config = new ConfigurationBuilder() 	    .SetBasePath(context.FunctionAppDirectory)                 // This gives yous access to your application settings                 // in your local development environs: 		.AddJsonFile("local.settings.json", optional: truthful, reloadOnChange: true)                 // This is what actually gets you the application settings in Azure 		.AddEnvironmentVariables()  		.Build(); 				 		string appsettingvalue = config["appsettingkey"]; 	}   } }        

Just like v3. Good stuff.

However, yous won't only need to add a reference to Microsoft.Extensions.Configuration and a new parameter "ExecutionContext context" to your function – see below:

          using Microsoft.Extensions.Configuration;  ...  namespace YourNamespace {   public static class YourClass   {     ...      [FunctionName("FunctionName")]     public static async Task RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "go", "mail service", Route = goose egg)]HttpRequest req, TraceWriter log, ExecutionContext context)     {       ...     }   } }        

You lot might also demand to add a NuGet package for Microsoft.Extensions.Configuration – should be easy enough!

Adding Microsoft.Extensions.Configuration Nuget package
Adding Microsoft.Extensions.Configuration NuGet package

All the same, with v2 your configuration might non quite be washed yet.

Your error might be something like this:

Error CS1061

'IConfigurationBuilder' does non contain a definition for 'AddEnvironmentVariables' and no accessible extension method 'AddEnvironmentVariables' accepting a first argument of type 'IConfigurationBuilder' could be found (are you missing a using directive or an associates reference?)

If y'all become an error for .SetBasePath(), .AddJsonFile() or .AddEnvironmentVariables(), basically merely add more NuGet packages until the consequence is resolved 😅 Sounds confusing, but the unlike configuration options are now actually granular – so you lot'll demand a few packages. I have listed them beneath…

There are a lot of NuGet packages to help y'all out! Start with these:

  • SetBasePath() requires:
    • Microsoft.Extensions.Configuration.Abstractions
  • AddJsonFile() requires:
    • Microsoft.Extensions.Configuration.FileExtensions
    • Microsoft.Extensions.Configuration.Json
  • AddEnvironmentVariables() requires:
    • Microsoft.Extensions.Configuration.EnvironmentVariables and possibly
    • Microsoft.Extensions.Configuration.UserSecrets

This rather granular approach to configurations might optimize the size and performance of the resulting software package, simply it does make parts of the evolution wheel just a bit frustrating :)

Accessing the settings in Azure Functions Runtime Version one

The i.ten generation of Azure Functions SDK uses the very traditional ConfigurationManager for accessing the Environmental variables or Awarding Settings. This case below shows how you lot tin can, for example, fetch the client id, client secret, and Azure AD domain information for apply later in the lawmaking:

          // C# ConfigurationManager example for Azure Functions v1 runtime var clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"]; var clientSecret = System.Configuration.ConfigurationManager.AppSettings["ClientSecret"]; var aadDomain = System.Configuration.ConfigurationManager.AppSettings["AADDomain"];        

Dainty and easy! ConfigurationManager is the good-old way of getting your hands on the settings. Information technology exposes AppSettings, which is just a NameValueCollection – with a key (or "proper noun"), you get back a string-typed value.

In a production workload, you might want to consider using Azure Key Vault instead of the app settings – but that's a topic for another article!

Accessing the settings in Azure Functions Runtime Versions one & 2 for .NET Cadre < 2.0

While you look at the model for managing the configurations in v2, and if you're not on v3 all the same, you lot might recollect adding a dozen NuGet packages looks like a fleck of an overkill. That's ok – if you only need to go application settings, there'southward a couple of shortcuts you can accept!

Remember the skillful old GetEnvironmentVariable() ? The one nosotros've been using since… Well, I suppose since .Net Framework 1.1!

Judge what? It still works!

So, if the simply affair you demand the configuration for is awarding settings, only run this to render value for central "ClientId":

          // C# Environment Variables example for Azure Functions v1 or v2 runtime  // This works all the way up to but non including .NET Core 2.0 var clientId = Environment.GetEnvironmentVariable("ClientId"); var clientSecret = Environment.GetEnvironmentVariable("ClientSecret"); var aadDomain = Environment.GetEnvironmentVariable("AADDomain");        

Interestingly enough, the GetEnvironmentVariable() doesn't seem to piece of work in .Internet Core ii.0 anymore, though.

A quick side note: In case you're not developing an Azure Role (but rather a Web App or something), you could inject the handy IConfiguration (from "Microsoft.Extensions.Configuration") parameter to the Startup method, and you lot henceforth y'all can admission the awarding settings like this:

          // C# Injected Configuration object instance // This works for .Cyberspace Core 1.x and later on!  public class Startup {   public Startup(IConfiguration configuration)   {     Configuration = configuration;   }    public IConfiguration Configuration { get; }    public void ConfigureServices(IServiceCollection services)   {     var clientId = Configuration["Values:ClientId"];      // The rest of the implementation omitted ...   } }        

… but for an Azure Part, yous don't have information technology available as is. Instead, utilize the way shown to a higher place for v1, v2, or v3.

Where are these configuration keys stored in?

Okay – back to basics for a second. Where do these unlike methods get their values from? Where do you demand to look at, if you're not getting what you're expecting?

For Azure Functions app settings, they're stored either locally in a configuration file, or when deployed, in the Azure (Part) App Service'south application settings (Platform Features > Configuration > Application settings).

And an example of a local configuration file ("local.settings.json") containing these values is beneath:

The contents look something like this:

          {  "IsEncrypted": false,  "Values": {   "AzureWebJobsStorage": "",   "AzureWebJobsDashboard": "",   "ClientID": "[your value here]", // "Application ID" from Azure Advertising app registration   "ClientSecret": "[your value hither]",   "AADDomain": "[your value here]"  } }        

This instance is for Azure Functions v2 or v3.

Meet more info

Beneath are a couple of groovy links for further reading:

  • https://docs.microsoft.com/en-usa/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1
  • https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.configurationbuilder?view=aspnetcore-2.1
  • https://blog.jongallant.com/2018/01/azure-function-config/ <– This guy's blog is a great resources for all Azure-related stuff, and so you should probably bookmark it.
  • Examples for accessing the awarding settings – there's ane for Creation DB, if that'southward your thing! https://vispud.blogspot.com/2019/05/azure-functions-database-connection.html
  • Author
  • Recent Posts

mm

How to Read App Settings in C#

Source: https://www.koskila.net/how-to-access-azure-function-apps-settings-from-c/

0 Response to "How to Read App Settings in C#"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel