Set and Read values from appsettings.json on ASP.NET Core / Web API

1, Add the following code on appsettings.json

{
  "ApplicationSettings": {
    "TestSetting": "TestValue"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}
2, Add ApplicationSettings class on Startup.cs
public class ApplicationSettings
{
    public string TestSetting { get; set; }
}
3, Add following code in the ConfigureServices method on Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddMvc();

    services.AddOptions();
    services.Configure<ApplicationSettings>(Configuration.GetSection("ApplicationSettings"));
}

4, How to call the configuration values on HomeController.cs for instance
[Route("api/[controller]")]
public class HomeController : Controller
{
    private IOptions<ApplicationSettings> _settings;
    public HomeController (IOptions<ApplicationSettings> settings)
    {
        _settings = settings;
    }

    [HttpGet("GetSetting", Name = "GetSetting")]
    public IActionResult GetSetting()
    {
        var testSetting = _settings.Value.TestSetting;
        return new ObjectResult(testSetting);
    }
}

Add Comment