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
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.
Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.
Nish's Technology Blog :
voidnish.wordpress.com