How To Read Values From App.settings File In Web API

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.

{
  "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.

  public class MicroservicesOptions
{
    public string? Application1 { get; set; }
    public string? Application2 { get; set; }
    public string? Application3 { get; set; }
}

Inject configurations in Startup.cs.

        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.

    public class ValuesController : ControllerBase
    {
        private readonly MicroservicesOptions _microservicesOptions;
        public ValuesController(IOptions<MicroservicesOptions> options)
        {
            _microservicesOptions = options.Value;
        }
    }