Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Hosted-services / Azure

Using IConfiguration and appsettings.json in a .NET Core Azure Function project

3.00/5 (3 votes)
2 Oct 2023CPOL 8.8K  

Introduction

For very basic Web APIs, HTTP triggered Azure functions are a very efficient and cost effective way to implement the service. One inconvenience though is that by default it does not come hooked up with an appsettings.json file or an IConfiguration instance. Fortunately, it’s not very difficult to hook those up.

Step 1

Add the following NuGet package to your project.

  • Microsoft.Azure.Functions.Extensions

Step 2

Add a startup.cs file to your project and insert the following code.

C#
[assembly: FunctionsStartup(typeof(Startup))]
 
public class Startup : FunctionsStartup
{
    public override void ConfigureAppConfiguration(
      IFunctionsConfigurationBuilder builder)
    {
        var context = builder.GetContext();
 
        builder.ConfigurationBuilder
            .AddJsonFile(
              Path.Combine(
                context.ApplicationRootPath, 
                "appsettings.json"), 
              optional: true, 
              reloadOnChange: false)
            .AddJsonFile(
              Path.Combine(
                context.ApplicationRootPath, 
                $"appsettings.{context.EnvironmentName}.json"), 
              optional: true, 
              reloadOnChange: false)
            .AddEnvironmentVariables();
    }
}

Step 3

Add your appsettings.json file and setup any configuration properties you need in there.

JavaScript
{
  "YourProperty": "some-value-here"
}

Step 4

Inject IConfiguration into your constructor. Note that the default function template won’t have a constructor as it uses a static class. Remove the static, and add the constructor.

C#
private readonly IConfiguration _configuration;
 
public SomeFunction(IConfiguration configuration)
{
    _configuration = configuration;
}

And now you can use it in the function as you’d normally do.

C#
[FunctionName("SomeFunction")]
public async Task<IActionResult> Run(
    [HttpTrigger(
      AuthorizationLevel.Anonymous, 
      "get", 
      "post", 
      Route = null)] 
    HttpRequest req,
    ILogger log)
{
  // Use _configuration["YourProperty"]
}

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)