How to read values from appsettings.json via IOptions Interface in Web API?
Define your properties in the key-value format in the Json file. I defined MicroservicesOptions in the Json file.
C#
{
"Logging": {
"LogLevel": {
"Default": "Information"
}
}
"MicroservicesOptions": {
"Application1": "App1",
"Application2": "App2",
"Application3": "App3"
}
}Make a class with the same properties, and make sure names should be exactly the same.
C#
public class MicroservicesOptions
{
public string? Application1 { get; set; }
public string? Application2 { get; set; }
public string? Application3 { get; set; }
}Inject configurations in Startup.cs.
C#
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.Configure<MicroservicesOptions>(Configuration.GetSection("MicroServices"));
}Now Inject a class containing properties in the constructor of your desired class where you need.
C#
public class ValuesController : ControllerBase
{
private readonly MicroservicesOptions _microservicesOptions;
public ValuesController(IOptions<MicroservicesOptions> options)
{
_microservicesOptions = options.Value;
}
}

Join the conversation! Your thoughts help the community grow.