Reading Appsettings in Web API

vamsiikrishna
2 min readJul 12, 2024

--

appsettings.json files contain important data such as database URLs, API keys that are used in the application.

In the asp.net core web API, we can read the appsettings.json file by configuring IOptions.

Let’s see how to do this.

  1. Create a Web API project.
  2. Go to appsettings.json and create a section called Database as shown below.
adding a field named Database.

3. Create a class in the models folder with properties as the fields in the section.

//you can create class with any name but properties should be same 
//as in the section.
public class Configurations{

public string Url { get; set; }
}

4. Add below line to configure the IOptions services.

builder.Services.Configure<Configurations>(
builder.Configuration.GetSection("Database")
);
//its configuring IOptions to the Configurations class
//from the given section.

5. You can use IOptions<Configurations> through constructor injection as shown in below code.

6. IOptions creates a singleton instance for the Configurations. so once the app is started,it won’t update its values as per appesettings.json updates.

7. Here comes, IOptionSnapshot<Configurations> that always reads the latest value from appsettings.json. It creates Scoped service.

app.MapGet("/options",(IOptions<Configurations> options,IOptionsSnapshot<Configurations> snapshot)=>{
//reading values.
var result=new{
Options=options.Value.Url,//to see updated value from appsettings.json, applications need to be restarted.
OptionsSnapshot=snapshot.Value.Url// always shows the updated content detials.
};

string json=JsonSerializer.Serialize(result);
Console.WriteLine(json);
return Results.Ok(result);
});

8. Let’s update appesetting.json Url to something and see the output now.

9. You can observe that OptionsSnapshot is showing the updated data.

conclusion: This is one of the heavily used approach to read options from appsettings in web applications.

--

--