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.
[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.
{
"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.
private readonly IConfiguration _configuration;
public SomeFunction(IConfiguration configuration)
{
_configuration = configuration;
}
And now you can use it in the function as you’d normally do.
[FunctionName("SomeFunction")]
public async Task<IActionResult> Run(
[HttpTrigger(
AuthorizationLevel.Anonymous,
"get",
"post",
Route = null)]
HttpRequest req,
ILogger log)
{
}
References