Using IOptions with .NET 6 API Endpoints

IOptions are a great way to pass configuration information around an application.

Here is a simple example of using them with the .NET API Endpoints. The code doesn’t need much explanation.

Create a new webapi application -

dotnet new webapi --name IOptionsInApiEndpoint

Replace the code in Program.cs with -

 1using Microsoft.Extensions.Options;
 2
 3var builder = WebApplication.CreateBuilder(args);
 4
 5builder.Services.AddOptions<ApplicationOptions>()
 6    .BindConfiguration(""); // reads the whole appsettings.json
 7
 8builder.Services.AddOptions<SubSection>()
 9    .BindConfiguration("SubSection"); // reads only the "SubSection" in appsettings.json
10
11var app = builder.Build(); 
12
13app.MapGet("/", (IOptions<ApplicationOptions> options) =>
14{
15    ApplicationOptions applicationOptions = options.Value;  
16   
17    return $"Name:{applicationOptions.Name}, Size:{applicationOptions.Size}, " +
18           $"SubSectionName:{applicationOptions.SubSection.SubSectionName}, " +
19           $"SubSectionId:{applicationOptions.SubSection.SubSectionId}";  
20});
21
22app.MapGet("/subsection", (IOptions<SubSection> options) =>
23{
24    SubSection subSectionOptions = options.Value;  
25   
26    return $"SubSectionName:{subSectionOptions.SubSectionName}, " +
27           $"SubSectionId:{subSectionOptions.SubSectionId}";  
28});
29
30app.Run();
31
32public class ApplicationOptions
33{
34    public string Name { get; set; }
35    public int Size { get; set; }
36    public SubSection SubSection { get; set; }
37}
38
39public class SubSection
40{
41    public string SubSectionName { get; set; }
42    public int SubSectionId { get; set; }
43}

Open appsettings.json and replace the content with -

{
  "Name": "ABC",
  "Size": 11,
  "SubSection": {
    "SubSectionName": "DEF",
    "SubSectionId": 22
  }
}
comments powered by Disqus

Related