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, is now available wherever you buy your books. 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.

3 Responses to APIs with C# – Part 4 Options

  1. I was looking through some of your articles on this internet site and I think this internet site is very instructive! Continue putting up.

  2. I haven’t checked in here for some time as I thought it was getting boring, but the last few posts are good quality so I guess I’ll add you back to my daily bloglist. You deserve it my friend 🙂

  3. Katie Jezek says:

    You are my inspiration , I possess few blogs and infrequently run out from to post : (.

Leave a Reply to transformational leadership book business Cancel reply

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