APIs with C# – Part 4 Options

NET provides support for passing options via environment variables, appsettings.json, and XML files. as well as command line arguments. In short, each higher level overrides the settings in lower levels.

To add options:

  1. Create a public class and name it (we’ll use funcOptions)
  2. Add a string property called returnValue (or name it whatever you like) and set the property to some value (e.g., MyOptions)
  3. We’re going to override that value in applications.json
  4. Add a property in appsettings.json (e.g., retVal) and set that property to a different value than we did in step 2

It’s time to set up the startup configuration. When you are done, your Program.cs should look like this:

var host = new HostBuilder()
.ConfigureFunctionsWebApplication()
.ConfigureServices((context, services) =>
{
  services.AddApplicationInsightsTelemetryWorkerService()
  .ConfigureFunctionsApplicationInsights()
  .AddOptions<MyOptions>
     .BindConfiguration("");
})
.Build();
host.Run();

The next step is to inject IOptions<MyOptions> and in the constructor set a member variable.

The Run method will look like this:

[Function("Function1")]
public IActionResult Run(HttpTrigger(AuthorizationLevel
  .Anonymous, "get", "post")] HttpRequest req)
{
   return new OKObjectResult(options.value.retValue);
}

 

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in APIs. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *