This is part 2 in our series on .NET APIs with C#. Find Part 1 here.
No surprise, the first step in building your application is to create a new solution. To get started, choose the Azure Functions template.
- Name your function, choose a location and click Next
- Select your runtime and hosting. Generally speaking, choose the latest LTS (Long Term Support) option
- Under authorization, choose Anonymous
- Under Function, select Http trigger
- Check Use Azurite (we’ll need this in a future post about durable functions)
- Click next and hey presto! your solution is created.
You should now have a solution with a Function. Right click on the project and select Add > New Azure Function. Now click Add and you will see a list of triggers. For this discussion, select Http Trigger.
.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:
- Create a public class and name it (we’ll use funcOptions)
- Add a string property called returnValue (or name it whatever you like) and set the property to some value (e.g., MyOptions)
- We’re going to override that value in applications.json
- 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); }
Next time we’ll take a look at Routing